cc-safety-net 2.0.3 → 2.0.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.
@@ -1,5 +1,5 @@
1
1
  var zX=[/\bgh[pousr]_[A-Za-z0-9]{20,}\b/g,/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,/\bglpat-[A-Za-z0-9_-]{20,}\b/g,/\bxox[abeprs]-[A-Za-z0-9-]{20,}\b/g,/\bnpm_[A-Za-z0-9_]{20,}\b/g,/\bpypi-[A-Za-z0-9_-]{20,}\b/g,/\b[rs]k_(?:live|test)_[A-Za-z0-9_]{20,}\b/g,/\bsk-[A-Za-z0-9_-]{20,}\b/g,/\bsk_[A-Za-z0-9]{20,}\b/g,/\bgsk_[A-Za-z0-9]{52,}\b/g,/\bxai-[A-Za-z0-9_-]{80,}\b/g,/\bpplx-[A-Za-z0-9_-]{20,}\b/g,/\bbastn_[A-Za-z0-9]{16,}\b/g,/\btgp_v1_[A-Za-z0-9_-]{43,}\b/g,/\bflp_[A-Za-z0-9]{10,}\b/g,/\bwfr_[A-Za-z0-9]{20,}\b/g,/\bfwp?_[A-Za-z0-9_-]{20,}\b/g,/\btp-[A-Za-z0-9_-]{20,}\b/g,/\bpsk-[A-Za-z0-9_-]{8,}-[A-Za-z0-9_-]{8,}\b/g,/\b[a-f0-9]{32}\.[A-Za-z0-9]{16}\b/g];function Q0($){let Z=$.replace(/\b((?:DATABASE|POSTGRES|POSTGRESQL|MYSQL|MARIADB|REDIS|MONGO(?:DB)?|DB)_DSN|CONNECTION_STRING)=("[^"]*"|'[^']*'|[^\s]+(?:\s+[A-Z_][A-Z0-9_]*=[^\s]+)*)/gi,"$1=<redacted>").replace(/\b((?:DATABASE|POSTGRES|POSTGRESQL|MYSQL|MARIADB|REDIS|MONGO(?:DB)?|DB)_(?:URL|URI|CONNECTION_STRING))=("[^"]*"|'[^']*'|[^\s]+)/gi,"$1=<redacted>").replace(/\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASS|KEY|CREDENTIALS)[A-Z0-9_]*)=("[^"]*"|'[^']*'|[^\s]+)/gi,"$1=<redacted>");return XZ(Z)}function XZ($){let Z=$.replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/gi,"<redacted>").replace(/((?:(['"])(?:authorization|cookie|x-api-key|api-key)\2|(?:authorization|cookie|x-api-key|api-key))\s*:\s*)(['"])(?:\\[^\r\n]|(?!\3)[^\\\r\n])*\3/gi,"$1$3<redacted>$3").replace(/(['"]?\s*(?:authorization|cookie|x-api-key|api-key)\s*:(?!\s*(?:"<redacted>"|'<redacted>'))\s*)([^'"\r\n]+)(['"]?)/gi,"$1<redacted>$3").replace(/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/:@]+):([^\s@/]+)@/gi,"$1<redacted>:<redacted>@").replace(/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/@:]+)@/gi,"$1<redacted>@").replace(/(^|[\s?&;|])((?:x-amz-signature|x-goog-signature|sig|signature)=)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^&#\s'"`;|<>()]*)/gi,"$1$2<redacted>").replace(/(^|\s)((?:-u|--user)(?:\s+|=))([^\s:]+):([^\s]+)/g,"$1$2<redacted>:<redacted>");for(let J of zX)Z=Z.replace(J,"<redacted>");return Z.replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g,"<redacted>").replace(/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g,"<redacted>")}function bX($){return KZ($).reduceRight((J,Q)=>`${J.slice(0,Q.valueStart)}<redacted>${J.slice(Q.valueEnd)}`,$)}function cL($){return XZ(bX($))}function dL($){return KZ($).map((Z)=>$.slice(Z.valueStart,Z.valueEnd))}function iL($){return/[A-Za-z_][A-Za-z0-9_]*=/.test($)}function KZ($){let Z=[],J=/[A-Za-z_][A-Za-z0-9_]*=/g;for(let Q of $.matchAll(J)){let X=Q.index,K=$[X-1];if(X>0&&K&&!/[\s"'([{]/.test(K))continue;let Y=X+Q[0].length;if(Y>=$.length)continue;Z.push({valueStart:Y,valueEnd:IX($,Y)})}return Z}function IX($,Z){if($.startsWith("$(",Z))return fX($,Z);let J=$[Z];if(J==='"'||J==="'"){for(let X=Z+1;X<$.length;X++)if(J==='"'&&$[X]==="\\")X++;else if($[X]===J)return X+1}let Q=Z;while(Q<$.length&&!/\s/.test($[Q]??""))Q++;return Q}function fX($,Z){let J=0,Q;for(let X=Z;X<$.length;X++){let K=$[X];if(Q){if(Q==='"'&&K==="\\")X++;else if(K===Q)Q=void 0;continue}if(K==='"'||K==="'"){Q=K;continue}if(K==="$"&&$[X+1]==="("){J++,X++;continue}if(K!==")")continue;if(J--,J===0)return X+1}return $.length}import{randomBytes as PX}from"node:crypto";import{closeSync as v3,constants as g$,fstatSync as y3,fsyncSync as CX,lstatSync as F0,mkdirSync as YZ,openSync as BZ,readdirSync as u3,readFileSync as AX,realpathSync as A0,renameSync as EX,rmdirSync as TX,statSync as w3,unlinkSync as h3,writeFileSync as SX}from"node:fs";import{isAbsolute as WZ,join as $$,normalize as yX,parse as qZ,relative as g3,resolve as k3,sep as x$}from"node:path";var wX=Symbol("PolicyFilesystemScope"),vX=Symbol("PolicyFilesystemTarget"),UZ=g$.O_NOFOLLOW??0;class u extends Error{constructor($){super(`Unable to access ${$} filesystem safely.`);this.name="PolicyFilesystemError"}}function D1($,Z){return{[wX]:!0,root:k3($),label:Z}}function l$($,Z){let J=yX(Z);if(Z===""||WZ(Z)||J===".."||J.startsWith(`..${x$}`))throw new u($.label);return{[vX]:!0,scope:$,relativePath:J,path:$$($.root,J)}}function X1($,Z){let J=g3($.root,k3(Z));return l$($,J)}function u2($,Z="rules policy"){let J=k3($),Q=qZ(J).dir;return l$(D1(Q,Z),g3(Q,J))}function X0($){try{if(!W1($,!1).exists)return null;let J=BZ($.path,g$.O_RDONLY|UZ);try{let Q=y3(J);if(!Q.isFile())throw new u($.scope.label);let X=AX(J,"utf-8"),K=F0($.path);if(!K.isFile()||K.isSymbolicLink()||Q.dev!==K.dev||Q.ino!==K.ino)throw new u($.scope.label);return W1($,!1),X}finally{v3(J)}}catch(Z){N0($.scope.label,Z)}}function GZ($,Z,J=384,Q){let X=`${$.path}.${PX(8).toString("hex")}.tmp`,K=null;try{gX($),W1($,!0),K=BZ(X,g$.O_CREAT|g$.O_EXCL|g$.O_WRONLY|UZ,J);let Y=y3(K);if(!Y.isFile())throw new u($.scope.label);SX(K,Z,"utf-8"),CX(K);let B=y3(K);if(!B.isFile()||B.dev!==Y.dev||B.ino!==Y.ino)throw new u($.scope.label);v3(K),K=null,W1($,!0),xX($,X,B.dev,B.ino),EX(X,$.path),Q?.($.path),W1($,!1)}catch(Y){if(K!==null)mX(K);pX(X),N0($.scope.label,Y)}}function HZ($,Z){if($.path===Z.path)return!0;try{if(!W1($,!1).exists||!W1(Z,!1).exists)return!1;return A0($.path)===A0(Z.path)}catch(J){if(J instanceof u)throw J;throw new u($.scope.label)}}function uX($){try{if(!W1($,!1,"directory").exists)return null;let J=u3($.path);return W1($,!1,"directory"),J}catch(Z){N0($.scope.label,Z)}}function oL($){let Z=uX($);if(!Z)return null;try{let J=Z.map((Q)=>{let X=l$($.scope,$$($.relativePath,Q)),K=F0(X.path);if(K.isSymbolicLink()||!K.isFile()&&!K.isDirectory())throw new u($.scope.label);return h2(LZ($.scope),A0(X.path),$.scope.label),{name:Q,kind:K.isDirectory()?"directory":"file"}});return W1($,!1,"directory"),J}catch(J){N0($.scope.label,J)}}function tL($){try{if(!W1($,!0).exists)return;h3($.path),W1($,!0)}catch(Z){N0($.scope.label,Z)}}function eL($){try{OZ($,$.relativePath.split(x$))}catch(Z){N0($.scope.label,Z)}}function $M($){try{if(!hX($))return;_Z($),W1($,!0,"directory")}catch(Z){N0($.scope.label,Z)}}function hX($){try{if(!W1($,!0,"directory").exists)return!1;return jZ($),!0}catch(Z){N0($.scope.label,Z)}}function W1($,Z,J="file"){let Q=x3($.scope);if(!Q)return{exists:!1};let X=$.relativePath.split(x$);for(let K of X.keys()){let Y=$$($.scope.root,...X.slice(0,K+1)),B=k$(Y);if(!B){if(K===X.length-1&&Z)return{exists:!1};return{exists:!1}}if(B.isSymbolicLink())throw new u($.scope.label);if(K<X.length-1&&!B.isDirectory())throw new u($.scope.label);if(K===X.length-1&&(J==="file"?!B.isFile():!B.isDirectory()))throw new u($.scope.label);h2(Q,A0(Y),$.scope.label)}return{exists:!0}}function jZ($){for(let Z of u3($.path)){let J=l$($.scope,$$($.relativePath,Z)),Q=F0(J.path);if(Q.isSymbolicLink()||!Q.isDirectory()&&!Q.isFile())throw new u($.scope.label);if(Q.isDirectory())jZ(J)}W1($,!1,"directory")}function _Z($){for(let Z of u3($.path)){let J=l$($.scope,$$($.relativePath,Z)),Q=F0(J.path);if(Q.isSymbolicLink())throw new u($.scope.label);if(Q.isDirectory()){_Z(J);continue}if(!Q.isFile())throw new u($.scope.label);h3(J.path)}TX($.path)}function gX($){OZ($,$.relativePath.split(x$).slice(0,-1))}function OZ($,Z){kX($.scope);let J=LZ($.scope);for(let Q of Z.keys()){let X=$$($.scope.root,...Z.slice(0,Q+1));if(!k$(X))YZ(X,{mode:448});let Y=F0(X);if(!Y.isDirectory()||Y.isSymbolicLink())throw new u($.scope.label);h2(J,A0(X),$.scope.label)}}function kX($){if(k$($.root)){if(!w3($.root).isDirectory())throw new u($.label);return}let Z=[],J=$.root;while(!k$(J)){Z.unshift(J);let Q=qZ(J).dir;if(Q===J)throw new u($.label);J=Q}if(!w3(J).isDirectory())throw new u($.label);for(let Q of Z){YZ(Q,{mode:448});let X=F0(Q);if(!X.isDirectory()||X.isSymbolicLink())throw new u($.label)}}function x3($){if(!k$($.root))return null;if(!w3($.root).isDirectory())throw new u($.label);return A0($.root)}function LZ($){let Z=x3($);if(!Z)throw new u($.label);return Z}function xX($,Z,J,Q){let X=F0(Z);if(!X.isFile()||X.isSymbolicLink()||X.dev!==J||X.ino!==Q)throw new u($.scope.label);let K=x3($.scope);if(!K)throw new u($.scope.label);h2(K,A0(Z),$.scope.label)}function h2($,Z,J){let Q=g3($,Z);if(Q===".."||Q.startsWith(`..${x$}`)||WZ(Q))throw new u(J)}function k$($){try{return F0($)}catch(Z){if(lX(Z)&&Z.code==="ENOENT")return null;throw Z}}function N0($,Z){if(Z instanceof u)throw Z;throw new u($)}function lX($){return $ instanceof Error&&"code"in $}function mX($){try{v3($)}catch{}}function pX($){try{h3($)}catch{}}import{homedir as rX}from"node:os";import{dirname as m1,isAbsolute as nX,join as T1,relative as aX,resolve as p1,sep as oX}from"node:path";var z1=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,g2="rulebook.json",k2=".cc-safety-net/rules";var MZ=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/,cX=/^[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9_.-]+$/,dX=/^[A-Za-z0-9._-]+$/,iX=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),sX="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l3=new RegExp(`^${iX}/(${z1.source.slice(1,-1)})/${sX}$`);function FZ($){return`.cc-safety-net/rules/${$}/rulebook.json`}function m$($){if(J$($))try{return Z$($),null}catch(Z){return Z instanceof Error?Z.message:String(Z)}return z1.test($)?null:`Local rulebook sources must be bare names matching ${z1}: ${$}`}function Z$($){if($.startsWith("github:"))throw Error(`Invalid rulebook source: ${$}`);let Z=$.match(MZ);if(!Z?.[1]||!Z[2]||!Z[3])throw Error(`Invalid GitHub rulebook source: ${$}`);let[J,Q,...X]=Z[3].split("/");if(!J||!dX.test(J))throw Error(`GitHub rulebook refs must be a single path segment: ${$}`);if(!Q||X.length>0||!z1.test(Q))throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${$}`);return{owner:Z[1],repo:Z[2],ref:J,path:FZ(Q),name:Q}}function NZ($){return cX.test($)}function J$($){return MZ.test($)}function m3($){if(!z1.test($))throw Error(`Local rulebook sources must be bare names matching ${z1}: ${$}`)}var RZ="rule.json",x2="policy.json",DZ="rule.lock",tX="config.json",zZ=".cc-safety-net",eX="rules",VZ="cache",$K="CC_SAFETY_NET_HOME",S1="`cc-safety-net rule sync`";function ZK($){return p1($??process.cwd(),k2)}function bZ($){return T1(ZK($),RZ)}function K0($){return $?.userConfigDir??($?.userConfigPath?m1($.userConfigPath):T1(JK(),eX))}function JK(){let $=process.env[$K];return $?p1($):T1(rX(),zZ)}function IZ($){return T1(K0($),RZ)}function WM($){return T1(K0($),DZ)}function E0($){return T1(m1($),DZ)}function qM($={}){return T1(m1(K0($)),tX)}function UM($={}){return p1($.cwd??process.cwd(),".safety-net.json")}function fZ($){let Z=$.userConfigPath??IZ($),J=$.projectConfigPath??bZ($.cwd),Q=PZ(Z,$),X=CZ(J,$);return{userConfigPath:Z,projectConfigPath:J,userLockPath:E0(Z),projectLockPath:E0(J),userScope:Q,projectScope:X,userConfigTarget:X1(Q,Z),projectConfigTarget:X1(X,J),userLockTarget:X1(Q,E0(Z)),projectLockTarget:X1(X,E0(J))}}function GM($){let Z=$.global?$.userConfigPath??IZ($):$.projectConfigPath??bZ($.cwd),J=$.global?PZ(Z,$):CZ(Z,$),Q=E0(Z);return{configDir:m1(Z),configPath:Z,lockPath:Q,filesystemScope:J,configTarget:X1(J,Z),lockTarget:X1(J,Q)}}function PZ($,Z){let J=Z.userConfigPath?m1(m1(p1(Z.userConfigPath))):m1(p1(Z.userConfigDir??K0(Z)));return D1(J,"user policy")}function CZ($,Z){let J=p1(Z.cwd??process.cwd()),Q=p1($),X=aX(J,Q);if(X!==".."&&!X.startsWith(`..${oX}`)&&!nX(X))return D1(J,"project policy");return D1(m1(m1(Q)),"project policy")}function AZ($){if($.kind==="github"&&$.display_ref)return`${$.owner}/${$.repo}#${$.display_ref}/${$.name}`;return $.spec}function l2($,Z){let J=$.digest.startsWith("sha256:")?$.digest.slice(7):$.digest;return T1(EZ(Z),"rulebooks",`${QK($)}--${J.slice(0,12)}`,g2)}function HM($){return T1(EZ($),"rulebooks")}function m2($,Z){let J=Z;return{cacheConfigDir:$,cwd:Z.cwd,global:J.global}}function QK($){return($.kind==="github"&&$.display_ref?`${$.owner}/${$.repo}#${$.display_ref}/${$.name}`:$.spec).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"rulebook"}function EZ($){let Z=$?.cacheConfigDir??K0($),J=$;if(J&&!J.global&&J.cwd&&p1(Z)===p1(J.cwd))return T1(p1(J.cwd),zZ,VZ);return T1(m1(Z),VZ)}import{lstatSync as TZ,readdirSync as XK,readFileSync as vZ,rmdirSync as KK,statSync as SZ,unlinkSync as YK,utimesSync as BK,writeFileSync as WK}from"node:fs";import{dirname as qK,join as Q$}from"node:path";var p2=30,p3=1,c3=365;function c2($){if(typeof $!=="number"||!Number.isInteger($))return 30;if($<1)return 1;return $>365?365:$}var i3=86400000,UK=".last-prune",GK=/^\d{4}-\d{2}$/,HK=/^((\d{4}-\d{2})-\d{2})-.+\.jsonl$/,yZ=($)=>Math.floor($/i3);function jK($){try{let Z=Q$(qK(K0($)),x2),J=JSON.parse(vZ(Z,"utf-8"));return c2(J?.audit?.retention_days)}catch{return p2}}function uZ($,Z=()=>new Date){try{let J=Z().getTime();if(!SZ($,{throwIfNoEntry:!1})?.isDirectory())return;let Q=Q$($,UK),X=SZ(Q,{throwIfNoEntry:!1})?.mtimeMs;if(X!==void 0&&yZ(X)===yZ(J))return;let K=J-jK()*i3,Y=new Date(J).toISOString().slice(0,7);for(let B of d3($)){if(B.isDirectory()){_K(Q$($,B.name),K,Y);continue}if(B.isFile()&&B.name.endsWith(".jsonl"))OK(Q$($,B.name),K)}WK(Q,"",{mode:384}),BK(Q,J/1000,J/1000)}catch{}}function _K($,Z,J){for(let Q of d3($)){if(!Q.isDirectory()||!GK.test(Q.name))continue;let X=Q$($,Q.name);for(let K of d3(X)){if(!K.isFile())continue;let Y=HK.exec(K.name);if(!Y||Y[2]!==Q.name)continue;let B=Date.parse(`${Y[1]}T00:00:00.000Z`)+i3;if(!Number.isFinite(B)||B>=Z)continue;hZ(Q$(X,K.name))}if(Q.name!==J)wZ(X)}wZ($)}function OK($,Z){try{let J=TZ($);if(J.mtimeMs>=Z)return;let Q=vZ($,"utf-8").split(`
2
- `).filter((X)=>X.trim()).map(LK);if(Q.length===0)return;if(Q.some((X)=>X===void 0||X>=Z))return;if(TZ($).mtimeMs!==J.mtimeMs)return;hZ($)}catch{}}function LK($){try{let Z=JSON.parse($).ts,J=typeof Z==="string"?Date.parse(Z):Number.NaN;return Number.isFinite(J)?J:void 0}catch{return}}function d3($){try{return XK($,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function hZ($){try{YK($)}catch{}}function wZ($){try{KK($)}catch{}}import{randomBytes as MK}from"node:crypto";import{appendFileSync as FK,mkdirSync as NK}from"node:fs";import{homedir as VK,userInfo as RK}from"node:os";import{isAbsolute as DK,join as s3}from"node:path";var zK="2.0.3",bK=1e4,IK=2000,fK=256,PK=32768;function CK($){let Z=$.trim();if(!Z)return null;let J=Z.replace(/[^A-Za-z0-9_.-]+/g,"_");if(J=J.replace(/^[._-]+|[._-]+$/g,"").slice(0,128),!J||J==="."||J==="..")return null;return J}function AK($){return($??"").replace(/[^A-Za-z0-9]/g,"-").slice(0,180)||"no-cwd"}function r3($,Z,J,Q,X,K={}){let Y=CK($);if(!Y)return;let B=K.homeDir??gZ();if(!B)return;let W=EK(B);if(!W)return;try{let q=(K.now??(()=>new Date))().toISOString(),U=d2(Q0(Z),bK),H=d2(Q0(J),IK),j=K.toolName?d2(Q0(K.toolName),fK):void 0,G=X===null?void 0:d2(Q0(X),PK),_=s3(W,AK(G?.value??null),q.slice(0,7));NK(_,{recursive:!0,mode:448});let O=s3(_,`${q.slice(0,10)}-${Y}.jsonl`),M={ts:q,id:(K.createId??(()=>MK(8).toString("hex")))(),v:zK,sessionId:Y,decision:K.decision??"deny",agent:K.agent,shape:K.shape,level:K.level,configFallback:K.configFallback,toolName:j?.value,command:U.value,segment:H.value,...U.truncated||H.truncated||j?.truncated||G?.truncated?{truncated:!0}:{},reason:Q,ruleId:K.ruleId,intent:K.intent,failureStage:K.failureStage,errorCode:K.errorCode,cwd:G?.value??null};FK(O,`${JSON.stringify(M)}
2
+ `).filter((X)=>X.trim()).map(LK);if(Q.length===0)return;if(Q.some((X)=>X===void 0||X>=Z))return;if(TZ($).mtimeMs!==J.mtimeMs)return;hZ($)}catch{}}function LK($){try{let Z=JSON.parse($).ts,J=typeof Z==="string"?Date.parse(Z):Number.NaN;return Number.isFinite(J)?J:void 0}catch{return}}function d3($){try{return XK($,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function hZ($){try{YK($)}catch{}}function wZ($){try{KK($)}catch{}}import{randomBytes as MK}from"node:crypto";import{appendFileSync as FK,mkdirSync as NK}from"node:fs";import{homedir as VK,userInfo as RK}from"node:os";import{isAbsolute as DK,join as s3}from"node:path";var zK="2.0.5",bK=1e4,IK=2000,fK=256,PK=32768;function CK($){let Z=$.trim();if(!Z)return null;let J=Z.replace(/[^A-Za-z0-9_.-]+/g,"_");if(J=J.replace(/^[._-]+|[._-]+$/g,"").slice(0,128),!J||J==="."||J==="..")return null;return J}function AK($){return($??"").replace(/[^A-Za-z0-9]/g,"-").slice(0,180)||"no-cwd"}function r3($,Z,J,Q,X,K={}){let Y=CK($);if(!Y)return;let B=K.homeDir??gZ();if(!B)return;let W=EK(B);if(!W)return;try{let q=(K.now??(()=>new Date))().toISOString(),U=d2(Q0(Z),bK),H=d2(Q0(J),IK),j=K.toolName?d2(Q0(K.toolName),fK):void 0,G=X===null?void 0:d2(Q0(X),PK),_=s3(W,AK(G?.value??null),q.slice(0,7));NK(_,{recursive:!0,mode:448});let O=s3(_,`${q.slice(0,10)}-${Y}.jsonl`),M={ts:q,id:(K.createId??(()=>MK(8).toString("hex")))(),v:zK,sessionId:Y,decision:K.decision??"deny",agent:K.agent,shape:K.shape,level:K.level,configFallback:K.configFallback,toolName:j?.value,command:U.value,segment:H.value,...U.truncated||H.truncated||j?.truncated||G?.truncated?{truncated:!0}:{},reason:Q,ruleId:K.ruleId,intent:K.intent,failureStage:K.failureStage,errorCode:K.errorCode,cwd:G?.value??null};FK(O,`${JSON.stringify(M)}
3
3
  `,{encoding:"utf-8",mode:384}),uZ(W,K.now)}catch{}}function d2($,Z){return{value:$.slice(0,Z),truncated:$.length>Z}}function gZ($=process.env.CC_SAFETY_NET_AUDIT_HOME||process.env.HOME){let Z=$||VK()||RK().homedir;return Z&&DK(Z)?Z:null}function EK($=gZ()){return $?s3($,".cc-safety-net","logs"):null}function xZ($,Z,J,Q=!0,X){if(Z.decision.kind==="allow"){if(!J||$.route.kind!=="command")return;let B=kZ($);return{decision:"allow",command:B,segment:B,reason:"allowed",cwd:$.context.executionCwd,toolName:$.toolName,level:Z.level,...Z.configFallback?{configFallback:!0}:{}}}let K=Z.decision.evidence.find((B)=>B.kind==="command"),Y=K?.command??(Q?kZ($):"");return{decision:"deny",command:Y,segment:K?.segment??Y,reason:Z.decision.reason,cwd:$.context.executionCwd,toolName:$.toolName,level:Z.level,...Z.configFallback?{configFallback:!0}:{},ruleId:Z.decision.ruleId,intent:Z.decision.intent,failureStage:X?.stage,errorCode:X?.errorCode}}function kZ($){return"command"in $?$.command??"":""}function lZ($,Z,J){if(!$)return;let Q;try{Q=Z()}catch{return}if(typeof Q!=="string"||!Q.trim())return;r3(Q,$.command,$.segment,$.reason,$.cwd,{homeDir:J.homeDir,decision:$.decision,agent:J.agent,shape:J.shape,level:$.level,configFallback:$.configFallback,toolName:$.toolName,ruleId:$.ruleId,intent:$.intent,failureStage:$.failureStage,errorCode:$.errorCode})}function EM($,Z,J){let Q;try{Q=Z()}catch{return}if(typeof Q!=="string"||!Q.trim())return;r3(Q,$.command??"",$.segment??$.command??"",$.reason,J.cwd??null,{homeDir:J.homeDir,decision:"deny",agent:J.agent,shape:J.shape,toolName:J.toolName??$.toolName,ruleId:$.ruleId,intent:$.intent})}var V0="Command could not be safely analyzed (strict mode). Simplify the command and retry, or ask the user to verify.",Y0="Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry.",mZ="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.",i2="CC Safety Net failed closed because command analysis failed unexpectedly. This is not caused by your command. Report it to the user.";function cZ($){let{reason:Z,command:J,segment:Q,toolName:X}=$,K=$.maxLen??200,Y=$.redact??((W)=>W),B=`BLOCKED by CC Safety Net
4
4
 
5
5
  Reason: ${Y(Z)}`;if($.ruleId)B+=`
@@ -57,8 +57,8 @@ ${TK($.intent??"manual_only")}`,B}function TK($){switch($){case"hard_stop":retur
57
57
  `}}function YH($){let Z=/^"\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})"$/.exec($),J=/^\$(?:([0-9]+|[@*])|\{([0-9]+|[@*])\})$/.exec($),Q=Z??J;if(!Q)return null;let X=Q[1]??Q[2];return{parameter:X==="@"||X==="*"?X:Number(X),quoted:Z!==null}}function BH($,Z,J,Q){let X=Z.slice(J+2);if($.parameter==="@")return $.quoted?G9(X):WH(X,Q);if($.parameter==="*"){let B=G9(X);if(!B)return;let W=B.join(Q[0]??"");return $.quoted?[W]:H9(W,Q)}let K=Z[J+1+$.parameter];if(K&&!J3(K))return;let Y=M2(K);return $.quoted?[Y]:H9(Y,Q)}function G9($){return $.every(J3)?$.map(S):void 0}function WH($,Z){let J=G9($);if(!J)return;let Q=J.map((X)=>H9(X,Z));return Q.some((X)=>X===void 0)?void 0:Q.flatMap((X)=>X??[])}function H9($,Z){if(["*","?","[","]"].some((J)=>$.includes(J)))return;if(Z==="")return $===""?[]:[$];if(Z===`
58
58
  `)return $.trim().split(/\s+/).filter(Boolean);if(Z.length!==1)return;return Z===" "||Z==="\t"||Z===`
59
59
  `?$.trim().split(/\s+/).filter(Boolean):$.split(Z).filter(Boolean)}function J3($){if(!$)return!0;return $.provenance==="unknown"?!/[$`]/.test(S($)):$.provenance==="literal"}function M2($){return $?S($):""}function qH($){return`'${$.replaceAll("'",`'"'"'`)}'`}function _9($,Z){return j9(w1($,"posix"),Z)}function R$($){return _9($,new Set(Array.from($.matchAll(v5)).flatMap((Z)=>{let J=Z[1]??Z[2];return J===void 0?[]:[J]})))}function j9($,Z){if($.status==="invalid"||$.status==="limited")return!1;let J=new Set(Z);for(let Q of $.nodes){if(Q.kind==="group"){if(j9(Q.body,J))return!0;continue}if(Q.kind!=="command")continue;if(Q.nested.some((X)=>j9(X,J))||k5(Q.words,J))return!0;_H(Q,J)}return!1}function k5($,Z){let J=$.findIndex((Y)=>s1(Y.text)===null);if(J===-1)return!1;let Q=$[J];if(!Q)return!1;if(F2(Q,Z))return!0;let X=x(Q.text);if(X==="source"||X==="."){let Y=$[J+1]?.text==="--"?J+2:J+1;return w5($[Y],Z)}if($1.has(X)){let Y=$.slice(J),B=t1(Y.map((q)=>q.text)),W=B.commandIndex??B.scriptIndex;return!B.syntaxCheck&&W!==null&&w5(Y[W],Z)}let K=UH($,J,Z);if(K===null)return!1;if(K===-1)return!0;return k5($.slice(K),Z)}function UH($,Z,J){let Q=x($[Z]?.text??"");if(Q==="command")return GH($,Z+1);if(Q==="exec")return HH($,Z+1);if(Q==="env")return jH($,Z+1,J);return null}function GH($,Z){for(let J=Z;J<$.length;J++){let Q=$[J]?.text??"";if(Q==="--")return $[J+1]?J+1:null;if(/^-[p]*[vV][pvV]*$/.test(Q))return null;if(/^-p+$/.test(Q))continue;return J}return null}function HH($,Z){for(let J=Z;J<$.length;J++){let Q=$[J]?.text??"";if(Q==="--")return $[J+1]?J+1:null;if(Q==="-a"){J++;continue}if(/^-a.+/.test(Q)||/^-[cl]+$/.test(Q))continue;return J}return null}function jH($,Z,J){for(let Q=Z;Q<$.length;Q++){let X=$[Q],K=X?.text??"";if(K==="--")return $[Q+1]?Q+1:null;if(K==="-S"||K==="--split-string")return F2($[Q+1],J)?-1:Q+2;if(K.startsWith("-S")||K.startsWith("--split-string="))return F2(X,J)?-1:Q+1;if(K==="-u"||K==="--unset"||K==="-C"||K==="--chdir"||K==="-P"){Q++;continue}if(K==="-i"||K==="-0"||K==="--null"||K.startsWith("-u=")||K.startsWith("--unset=")||K.startsWith("-C")||K.startsWith("--chdir=")||K.startsWith("-P"))continue;if(K.startsWith("-"))continue;if(s1(K))continue;return Q}return null}function _H($,Z){if(!$.words.every((J)=>s1(J.text)!==null))return;for(let J of $.words){let Q=s1(J.text);if(!Q)continue;if(F2(J,Z))Z.add(Q.name)}}function F2($,Z){if(!$)return!1;return $.parts.filter((J)=>J.provenance==="variable").some((J)=>Array.from(J.raw.matchAll(v5)).some((Q)=>{let X=Q[1]??Q[2];return X!==void 0&&(ZH.test(X)||Z.has(X))}))}function w5($,Z){return!!$&&($.parts.some((J)=>J.provenance!=="literal"&&J.provenance!=="variable")||F2($,Z))}var OH=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--config-env"]),LH=new Set(["-c","-H","-l","--config","--context","--host","--log-level","--tlscacert","--tlscert","--tlskey"]),MH=new Set;function x5($){if($==="git")return OH;if($==="docker")return LH;return MH}function Q1($,Z){if($.length===0||Z.length===0)return null;let J=x($[0]??""),Q=O1($);for(let X of Z){if(!FH(J,X.command))continue;if(!NH(J,$,X.subcommand))continue;if(RH($,new Set(X.block_args),Q))return{id:`custom.${X.name}`,reason:`[${X.name}] ${X.reason}`,intent:X.intent??"manual_only"}}return null}function FH($,Z){return $===x(Z)}function NH($,Z,J){if(!J)return!0;return l5(Z,1,J,x5($))}function l5($,Z,J,Q){let X=!1;for(let K=Z;K<$.length;K++){let Y=$[K];if(!Y)continue;if(X){X=!1;continue}if(Y==="--"){let B=$[K+1];if(B&&!B.startsWith("-"))return B===J;return!1}if(Q.has(Y)){X=!0;continue}if(Y.startsWith("-")){if(!Y.includes("=")&&VH($,K,J,Q))return!0;continue}return Y===J}return!1}function VH($,Z,J,Q){let X=$[Z+1];if(!X||X.startsWith("-"))return!1;return l5($,Z+2,J,Q)}function RH($,Z,J){for(let Q of $)if(Z.has(Q))return!0;for(let Q of J)if(Z.has(Q))return!0;return!1}function P0($,Z,J={}){if($.length===0)return null;let Q=$[0];if(!Q)return null;let X=x(Q);if(X==="eval"){let K=V$(g($));if(K.kind==="dynamic")return D$(J,Z);if(K.kind==="literal"&&Z.analyzeNested){let Y=Z.analyzeNested(K.source,{effectiveCwd:Z.cwd,envAssignments:Z.envAssignments});if(Y)return Y}return $0(J,Z)}if($1.has(X)){if(C1($))return null;let K=o1($);if(K){if(J.dynamicSourceInput??J.dynamicInput){let W=D$(J,Z);if(W)return W}if(R$(K)){let W=D$(J,Z);if(W)return W}if(!Z.analyzeNested)return null;let B=Z.analyzeNested(K,{effectiveCwd:Z.cwd,envAssignments:Z.envAssignments});if(B)return B;return null}let Y=e1(g($));if(Y.kind==="dynamic")return D$(J,Z);if(Y.kind==="literal"){if(J.dynamicSourceInput)return D$(J,Z);return null}if(J.dynamicSourceInput??J.dynamicInput)return D$(J,Z);return null}if(F1.has(X))return T(S4($,(K)=>Z.analyzeNested?Z.analyzeNested(K,{effectiveCwd:Z.cwd,envAssignments:Z.envAssignments}):null),Z.policy)??Q1($,Z.policy?.rules??[])??$0(J,Z);if(N1(X)){let K=h4($);if(!K)return $0(J,Z);if(a(Z.policy,"interpreter.one-liner-paranoid",!!Z.paranoidInterpreters)){let B=T(N("interpreter.one-liner-paranoid",O$),Z.policy);if(B)return B}if(x4(X,K))return $0(J,Z);let Y=Z.analyzeNested?.(K,{effectiveCwd:Z.cwd,envAssignments:Z.envAssignments});if(Y&&Y.id!=="raw-text.dangerous-command"&&(Y.reason!==V0||U$(K)))return Y;if(L$(K,Z.scanWork))return T(N("interpreter.dangerous-command",k0),Z.policy)??$0(J,Z);return $0(J,Z)}if(X==="rm"||X==="rmdir"){let K=X==="rm"&&(H0($)||J.dynamicRmInput);return T(N$(g($),{environment:Z.environment,cwd:Z.cwd,originalCwd:Z.originalCwd,strict:Z.strict,paranoid:Z.paranoidRm,allowTmpdirVar:Z.allowTmpdirVar,tmpdirWordSplittingUnsafe:a1(Z.envAssignments,Z.environment),trustedTmpdirValue:G0(Z.envAssignments,Z.environment),protectedGitMetadata:Z.protectedGitMetadata,policy:Z.policy}),Z.policy)??(K&&J.dynamicRmInput?$0(J,Z):null)??(K?DH(J,Z):null)}if(X==="find")return t4(g($),{...Z,derivedCommandWorkBudget:Z.derivedCommandWorkBudget,analyzeTokens:(K,Y)=>P0(K,{...Z,cwd:Y??void 0,derivedCommandWorkBudget:Z.derivedCommandWorkBudget},J)})??Q1($,Z.policy?.rules??[])??$0(J,Z);if(X==="git")return T(F$(g($),{env:Z.environment.env,cwd:Z.cwd,envAssignments:Z.envAssignments,policy:Z.policy,worktreeMode:J.dynamicInput?!1:Z.worktreeMode}),Z.policy)??Q1($,Z.policy?.rules??[])??$0(J,Z);return Q1($,Z.policy?.rules??[])??$0(J,Z)}function D$($,Z){return $.shellDynamicMatch?T($.shellDynamicMatch,Z.policy):null}function $0($,Z){return $.dynamicSourceInput&&$.dynamicSourceMatch?T($.dynamicSourceMatch,Z.policy):null}function DH($,Z){return $.dynamicInput&&$.rmDynamicMatch?T($.rmDynamicMatch,Z.policy):null}var O9="xargs rm -rf with dynamic input is dangerous. Use explicit file list instead.",L9="xargs dynamic input can supply arbitrary executable command source. Use an explicit child command and arguments instead.",zH="__CC_SAFETY_NET_XARGS_INPUT__",Q3="__CC_SAFETY_NET_XARGS_INTERPRETER_INPUT__",X3="rm",bH=/(?:^|[;&|]\s*|\b(?:eval|source)\s+|\b(?:ba|da|z|k)?sh\s+-c\s+)\s*["']?\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,IH=/(?:^|[;&|]\s*)\s*eval\b((?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\\'";&|\r\n])*)/g,fH=/\$(?:([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)|\{!?([0-9]+|[@*]|[A-Za-z_][A-Za-z0-9_]*)(?:[^}]*)\})/g,PH=/^(?:[0-9]+|[@*])$/,CH=new Set(["branch","checkout","clean","push","reset","restore","switch","tag"]);function c5($,Z){let J=$.map(S),{childStart:Q,replacementToken:X}=i0(J),K=J.slice(Q),Y=N("xargs.shell-dynamic",L9);if(EH(K,X,Z)&&T(Y,Z.policy))return T(Y,Z.policy);for(let B of k1(K,Z)){let W=B.tokens,q=X!==null&&W[0]!==K[0]&&(W[0]?.includes(X)??!1)?T(Y,Z.policy):null;if(q)return q;let U=r5(W,X,B.wrapperEnvAssignments),H=B.head==="rm"&&X!==null&&i5(W,X),j=P0(W,{...Z,cwd:B.cwd,envAssignments:B.envAssignments},{dynamicInput:U,dynamicSourceInput:H||d5(W,B.head,X,B.wrapperEnvAssignments,U,Z.scanWork,Z.environment),dynamicRmInput:H,shellDynamicMatch:Y,dynamicSourceMatch:Y,rmDynamicMatch:N("xargs.rm-recursive-force-dynamic",O9)});if(j)return j;let G=AH(W,X,Z.policy?.rules??[]);if(G)return G;if(B.head==="git"){let O=X===null?[...W,zH]:W,M=X!==null&&(W.some((D)=>D.includes(X))||Array.from(B.envAssignments.values()).some((D)=>D.includes(X))),L=P0(O,{...Z,cwd:B.cwd,envAssignments:B.envAssignments,worktreeMode:X===null||M?!1:Z.worktreeMode});if(L)return L}let _=Q1(W,Z.policy?.rules??[]);if(_)return _}return null}function AH($,Z,J){if(J.length===0)return null;if(Z===null){for(let X of J){let K=Q1([...$,...X.subcommand?[X.subcommand]:[],...X.block_args],J);if(K)return K}return null}let Q=new Set(J.flatMap((X)=>[X.subcommand,...X.block_args].flatMap((K)=>K?$.flatMap((Y)=>M9(Y,Z,K)):[])));for(let X of Q){let K=Q1($.map((Y)=>Y.replaceAll(Z,X)),J);if(K)return K}return null}function M9($,Z,J){let Q=$.indexOf(Z);if(Q===-1||$.indexOf(Z,Q+Z.length)!==-1)return[];let X=$.slice(0,Q),K=$.slice(Q+Z.length);return J.startsWith(X)&&J.endsWith(K)?[J.slice(X.length,J.length-K.length)]:[]}function d5($,Z,J,Q,X,K,Y){if($1.has(Z)){if(C1($))return!1;if(J!==null&&TH($,J))return!0;let B=o1($);if(!B){let W=e1(g($));if(W.kind==="literal")return J!==null&&W.source.includes(J);return W.kind==="none"&&X}if(J!==null&&B.includes(J))return!0;if(q2(B,K))return!0;return SH(B,J,Q)}if(N1(Z))return m5($,J,k4,C7(Z));if(F1.has(Z))return m5($,J,u6,L7);if(Z==="eval"){let B=V$(g($));if(B.kind==="dynamic")return!0;if(J!==null)return B.kind==="literal"&&B.source.includes(J);return X}if(Z==="find")return yH($,J,K,Y);if(Z==="git"){let B=x1($);return J===null?B.subcommand===null:(B.subcommand?.includes(J)??!1)||B.subcommand!==null&&CH.has(B.subcommand.toLowerCase())&&s5(B.rest,J).some((W)=>W.includes(J))}return!1}function m5($,Z,J,Q){let X=J($);if(Z===null)return X.optionsOpen||J([...$,Q3]).sources.some((W)=>W.value===Q3);if(X.sources.some((W)=>W.value.includes(Z)))return!0;let K=new Set(X.sources.map((W)=>`${W.tokenIndex}\x00${W.kind}\x00${W.value}`)),Y=Q.flatMap((W)=>[W.selector,...W.valueForm==="attached-only"||W.valueForm==="attached-or-separate"?[`${W.selector}${Q3}`]:[],...W.valueForm==="equals-or-separate"?[`${W.selector}=${Q3}`]:[]]),B=new Set(Y.flatMap((W)=>$.flatMap((q)=>M9(q,Z,W))));return Array.from(B).some((W)=>J($.map((q)=>q.replaceAll(Z,W))).sources.some((q)=>!K.has(`${q.tokenIndex}\x00${q.kind}\x00${q.value}`)))}function EH($,Z,J){if($.length===0||($[0]??"").toLowerCase()==="command")return!1;let Q=new Set(Array.from(k1($,J),(K)=>K.head)),X=Z===null?[...$,X3]:$.map((K,Y)=>Y===0?K:K.replaceAll(Z,X3));return Array.from(k1(X,J)).some((K)=>K.head===X3&&!Q.has(X3))}function i5($,Z){return s5($.slice(1),Z).some((J)=>J.includes(Z)&&(J.startsWith("-")||J.startsWith(Z)))}function s5($,Z){let J=$.findIndex((Q)=>Q==="--"&&!Q.includes(Z));return J===-1?$:$.slice(0,J)}function r5($,Z,J){if(Z===null)return!0;return $.some((Q)=>Q.includes(Z))||Array.from(J.values()).some((Q)=>Q.includes(Z))}function TH($,Z){let J=t1($);if(J.commandIndex!==null&&($[J.commandIndex]??"").includes(Z)||J.scriptIndex!==null&&($[J.scriptIndex]??"").includes(Z))return!0;return["-c","-nc","-cn",`--${Z}`,Z].some((X)=>$.some((K,Y)=>{if(Y===0||!K.includes(Z))return!1;return M9(K,Z,X).some((W)=>{let q=$.map((H,j)=>j===Y?H.replaceAll(Z,W):H),U=t1(q);if(U.commandIndex===null&&U.scriptIndex===null)return!1;if(J.commandIndex===null&&U.commandIndex!==null)return!0;if(J.scriptIndex===null&&U.scriptIndex!==null)return!0;if(U.commandIndex!==null&&(q[U.commandIndex]??"").includes(W))return!0;return U.scriptIndex!==null&&(q[U.scriptIndex]??"").includes(W)})}))}function SH($,Z,J){let Q=new Set(Z===null?[]:Array.from(J).filter(([,X])=>X.includes(Z)).map(([X])=>X));for(let X of $.matchAll(bH))if(p5(X,Q))return!0;for(let X of $.matchAll(IH))for(let K of(X[1]??"").matchAll(fH))if(p5(K,Q))return!0;return _9($,Q)}function p5($,Z){let J=$[1]??$[2];return J!==void 0&&(PH.test(J)||Z.has(J))}function yH($,Z,J,Q){if(Z===null)return!0;let X=!1,K=0;for(let Y=1;Y<$.length;Y++){let B=$[Y]??"";if(!X&&!B.startsWith("-")&&B!=="!"&&B!=="("){if(B.indexOf(Z)===0)return!0;continue}if(X=!0,K>0){K--;continue}if(j0(B)){let q=_2($,Y);Y=q.nextIndex-1;for(let U of k1(q.tokens,{environment:Q,cwd:void 0})){let H=r5(U.tokens,Z,U.wrapperEnvAssignments);if(U.head==="rm"&&i5(U.tokens,Z)||d5(U.tokens,U.head,Z,U.wrapperEnvAssignments,H,J,Q))return!0}continue}let W=I0(B);if(W>0){if(K=W,B.includes(Z))return!0;continue}if(B.includes(Z))return!0}return!1}function i0($){let Z=new Set(["-L","-n","-P","-s","-a","-E","-R","-S","-e","-d","-J","--max-args","--max-procs","--max-chars","--arg-file","--eof","--delimiter","--max-lines","--process-slot-var"]),J=null,Q=1;while(Q<$.length){let X=$[Q];if(!X)break;if(X==="--")return{childStart:Q+1,replacementToken:J};if(X.startsWith("-")){if(X==="-I"){J=$[Q+1]??"{}",Q+=2;continue}if(X.startsWith("-I")&&X.length>2){J=X.slice(2),Q++;continue}if(X==="--replace"){J="{}",Q++;continue}if(X.startsWith("--replace=")){let K=X.slice(10);J=K===""?"{}":K,Q++;continue}if(X==="-J"){J=$[Q+1]??"{}",Q+=2;continue}if(Z.has(X))Q+=2;else Q++}else return{childStart:Q,replacementToken:J}}return{childStart:$.length,replacementToken:J}}var N2="parallel rm -rf with dynamic input is dangerous. Use explicit file list instead.",V2="parallel with shell -c can execute arbitrary commands from dynamic input. Run the inner command directly on an explicit file list instead.",vH="parallel without a command reads executable commands from dynamic input. Use an explicit command template or ::: arguments instead.",uH="parallel command construction cannot be verified safely. Use the default ::: separator, literal arguments, and built-in replacement strings.",hH=/\{[^{}\s]*\}/,QJ=/\{\}|\{-?\d+\}/g,gH=new Set(["branch","checkout","clean","merge","push","rebase","reflog","reset","restore","stash","switch","tag","worktree"]),kH=["e","f","source","file","-e","-f","--source","--file"],xH=["c","e","eval","m","r","Mmodule","import","require","-c","-e","-m","-r","--eval","--import","--require"],lH=new Set(["-L","-d","-n","--delay","--delimiter","--header","--joblog","--jl","--max-args","--max-lines","--nice","--results","--result","--res","--tagstring","--timeout"]),mH=new Set(["--arg-file","--colsep","--rpl","--arg-sep","--arg-file-sep"]),n5=new Set(["-S","--sshlogin","--slf","--sshloginfile"]),pH=new Set(["--workdir","--wd"]),a5="__CC_SAFETY_NET_PARALLEL_SOURCE__",cH=new TextEncoder,Y3=E.maxDerivedBytes+4*E.maxPlaceholderReplacements;function q1($,Z){for(let J of $){let Q=Z(J);if(Q)return Q}return null}function XJ($,Z){let J=$.map(S);if((Z.envAssignments?.has("PARALLEL")?Z.envAssignments.get("PARALLEL"):Z.environment.env.get("PARALLEL"))?.trim()){let O=r0(Z);if(O)return O}if(J.length===2&&(J[1]==="--version"||J[1]==="--help"))return null;let X=LJ(J),{template:K,jobs:Y,runsRemotely:B,envNames:W,readsCommandsFromInput:q,unsupported:U,workdir:H,dryRun:j}=X;if(U){let O=r0(Z);if(O)return O}if(q){let O=tH(Z);if(O)return O}if(H!==void 0&&B){let O=r0(Z);if(O)return O}let G=Qj(H,Z.cwd,Z.environment.paths);if(G===null){let O=r0(Z);if(O)return O}let _=B?{...Z,cwd:void 0,originalCwd:void 0}:G===null||G===void 0||G===Z.cwd?Z:{...Z,cwd:G};if(j){let O=[...k1(K,_)];if((O.length===0?V9(W,Z.envAssignments,new Map).values:O.flatMap((L)=>V9(W,Z.envAssignments,L.envAssignments).values)).some(z9)){let L=r0(Z);if(L)return L}return null}if(K.length===0){if(W.length>0||Y.some((L)=>L.length!==1)){let L=r0(Z);if(L)return L}let O=Y.map((L)=>L[0]??"");V1(Z.budget,N9(O));let M=HJ(_.envAssignments,_.cwd,B);return q1(O,(L)=>Z.analyzeNested(L,M))}return q1(k1(K,_),(O)=>dH(O,X,Z,_))}function dH($,Z,J,Q){let{jobs:X,templateHasPlaceholder:K,runsRemotely:Y,usesStdin:B,envNames:W}=Z,q=$.tokens,U={...Q,cwd:$.cwd,envAssignments:$.envAssignments},H=V9(W,J.envAssignments,$.envAssignments);if(H.entries.some((L)=>_J(L.value))){let L=r0(J);if(L)return L}let j=H.entries.some((L)=>L.hasPlaceholder),G=K||j,_=B&&G,O=HJ($.envAssignments,$.wrapperCwd,Y||_);if($1.has($.head)){let L=()=>{if(!K||X.length===0)return null;return V1(J.budget,K3(q,X,"generic")),q1(X,(f)=>P0(q.map((A)=>Z0(A,f)),U))};if(C1(q))return L();let D=o1(q);if(D){if(OJ(D)){let b=s0(J);if(b)return b;if(X.length===0)return null;return V1(J.budget,ZJ(D,X)),q1(X,(I)=>J.analyzeNested(Z0(D,I),O))}if(l(D)){if(X.length>0)return V1(J.budget,ZJ(D,X)),q1(X,(C)=>J.analyzeNested(Z0(D,C),O));V1(J.budget,e5(D));let b=O2(D);if(b?.[0]&&x(b[0])==="rm"&&H0(b)){let C=t5(J);if(C)return C}let I=b?P0(b,U,{dynamicInput:B,shellDynamicMatch:N("parallel.shell-dynamic",V2),rmDynamicMatch:N("parallel.rm-recursive-force-dynamic",N2)}):null;if(I)return I;return J.analyzeNested(D,O)}let f=!j&&(!K||X.length>0)?(X.length>0?X:[void 0]).map((b)=>Z3(g(b===void 0?q:K?q.map((I)=>Z0(I,b)):[...q,...b]),D)):[];if(f.some((b)=>b.kind==="dynamic")){let b=s0(J);if(b)return b}let A=f.flatMap((b)=>b.kind==="literal"?[b.source]:[]);if(A.length>0)return V1(J.budget,N9(A)),q1(A,(b)=>J.analyzeNested(b,O));V1(J.budget,$j(e5(D),eH(H.entries,X)));let F=R$(D);if(F&&H.entries.length>0){let b=JJ(H,X,Q,Y);if(b)return b}if(F){let b=s0(J);if(b)return b}let R=J.analyzeNested(D,O);if(R)return R;if(!F){let b=JJ(H,X,Q,Y);if(b)return b}if(G)return s0(J);return null}let z=e1(g(q));if(z.kind==="dynamic"||z.kind==="literal"&&l(z.source))return s0(J)??L();if(z.kind==="literal")return L();if(X.length>0){let f=s0(J);if(f)return f;let A=L();if(A)return A;if(K)return null;let F=X.flatMap((R)=>R[0]===void 0?[]:[R[0]]);return V1(J.budget,N9(F)),q1(F,(R)=>J.analyzeNested(R,O))}if(G||B)return s0(J)??L();return null}if($.head==="rm"&&H0(q)){if(K&&X.length>0)return V1(J.budget,K3(q,X,"rm")),q1(X,(D)=>F9(q.map((z)=>R9(z,D)),$.cwd,Q));if(X.length>0)return V1(J.budget,$J(q,X)),q1(X,(D)=>F9([...q,...D],$.cwd,Q));let L=F9(q.flatMap((D,z)=>{if(z===0||!l(D))return[D];return D.startsWith("-")?[R9(D,[""])]:[]}),$.cwd,Q);if(L)return L;return t5(J)}V1(J.budget,K&&X.length>0?K3(q,X,"generic"):X.length>0?$J(q,X):WJ(q));let M=X.length>0?X:[void 0];return q1(M,(L)=>{let D=L===void 0?q:K?q.map((C)=>Z0(C,L)):[...q,...L],z=N("parallel.shell-dynamic",V2),f=B&&$.head==="find"?oH(D,Q):null,A=YJ(D,B,J.policy?.rules??[],J.budget)??f?.customResult??null,F=x($.head),R=B&&(F==="rm"&&D9(D)||F==="xargs"&&BJ(D)||f?.rmOptions===!0),b=B&&(R||f?.executedSource===!0||f===null&&KJ(D,F)),I=P0(D,{...U,worktreeMode:Y||B||G?!1:J.worktreeMode},{dynamicInput:B||G,dynamicRmInput:R,dynamicSourceInput:A!==null||b,shellDynamicMatch:z,dynamicSourceMatch:z,rmDynamicMatch:N("parallel.rm-recursive-force-dynamic",N2)});if(b){let C=T(z,J.policy);if(C)return C}return I??A??Q1(D,J.policy?.rules??[])})}function KJ($,Z){if(l($[0]??""))return!0;if(Z==="eval"||Z==="source"||Z===".")return!0;if(Z==="parallel"||Z==="xargs")return!0;if($1.has(Z))return rH($);if(Z==="git")return iH($);if(Z==="find")return!0;if(F1.has(Z))return o5($,kH,X2);if(N1(Z))return o5($,xH,g4);return!1}function D9($){let Z=$.indexOf("--"),J=$.slice(1,Z===-1?void 0:Z);if(!$.some(l))return Z===-1;return J.some((X)=>l(X)&&(X.startsWith("-")||OJ(X)))}function iH($){if(sH($))return!0;let Z=x1($);if(Z.subcommand===null||l(Z.subcommand))return!0;if(!gH.has(Z.subcommand.toLowerCase()))return!1;let J=Z.rest.indexOf("--"),Q=Z.rest.slice(0,J===-1?void 0:J);if(!$.some(l))return J===-1;return Q.some(l)}function sH($){for(let Z=1;Z<$.length;Z++){let J=$[Z];if(!J||J==="--"||!J.startsWith("-"))return!1;if(J==="-c"||J==="--config-env"){if(l($[Z+1]??""))return!0;Z++;continue}if(J.startsWith("-c")&&J.length>2||J.startsWith("--config-env=")){if(l(J))return!0;continue}if(l(J))return!0}return!1}function rH($){if(C1($))return!1;let Z=o1($);if(Z!==null)return l(Z);let J=e1(g($));if(J.kind==="literal")return l(J.source);if(J.kind==="dynamic")return!0;return!$.some(l)}function o5($,Z,J){let Q=J($);if(Q.some((K)=>l(K.value)))return!0;if(!$.some(l))return J([...$,a5]).some((K)=>K.value===a5);let X=new Set(Q.map((K)=>`${K.tokenIndex}\x00${K.kind}\x00${K.value}`));return Z.some((K)=>J($.map((Y)=>Z0(Y,[K]))).some((Y)=>!X.has(`${Y.tokenIndex}\x00${Y.kind}\x00${Y.value}`)))}function YJ($,Z,J,Q){if(!Z||J.length===0)return null;let X=J.filter((Y)=>x(Y.command)===x($[0]??""));if(X.length===0)return null;let K=$.some(l);if(V1(Q,nH($,X,K)),!K)return q1(X,(Y)=>Q1([...$,...Y.subcommand?[Y.subcommand]:[],...Y.block_args],[Y]));return q1(X,(Y)=>{let B=new Set([Y.subcommand,...Y.block_args].flatMap((W)=>W?aH($,W):[]));return q1(B,(W)=>Q1($.map((q)=>Z0(q,[W])),[Y]))})}function nH($,Z,J){let Q=J?j1(t(Z.map((X)=>X.block_args.length+(X.subcommand?1:0)),E.maxChildAnalyses),2*Math.max($.length,1),E.maxChildAnalyses):Z.length;return{childAnalyses:Q,derivedTokens:j1(Q,$.length,E.maxDerivedTokens)}}function aH($,Z){return $.flatMap((J)=>{let Q=[...J.matchAll(/\{[^{}\s]*\}/g)];if(Q.length!==1)return[];let X=Q[0];if(!X||X.index===void 0)return[];let K=J.slice(0,X.index),Y=J.slice(X.index+X[0].length);if(!Z.startsWith(K)||!Z.endsWith(Y))return[Z];let B=Z.slice(K.length,Z.length-Y.length);return B!==Z?[Z,B]:[Z]})}function oH($,Z){let J={customResult:null,executedSource:!$.some(l),rmOptions:!1},Q=!1,X=0,K=null,Y=()=>{if(!K?.some(l))return;for(let B of k1(K,Z))J.executedSource||=KJ(B.tokens,B.head),J.rmOptions||=B.head==="rm"&&D9(B.tokens)||B.head==="xargs"&&BJ(B.tokens),J.customResult??=YJ(B.tokens,!0,Z.policy?.rules??[],Z.budget)};for(let B of $.slice(1)){if(!Q&&!B.startsWith("-")&&B!=="!"&&B!=="("){J.executedSource||=l(B);continue}if(Q=!0,K){if(B===";"||B==="+"){Y(),K=null;continue}K.push(B);continue}if(X>0){X--;continue}if(j0(B)){K=[],J.executedSource||=l(B);continue}let W=I0(B);if(W>0){X=W,J.executedSource||=l(B);continue}J.executedSource||=l(B)}return Y(),J}function BJ($){let Z=$.slice(i0($).childStart);return x(Z[0]??"")==="rm"&&D9(Z)}function B3($,Z){return(J)=>T(N($,Z),J.policy)}var s0=B3("parallel.shell-dynamic",V2),tH=B3("parallel.command-stream-dynamic",vH),r0=B3("parallel.command-stream-dynamic",uH),t5=B3("parallel.rm-recursive-force-dynamic",N2);function F9($,Z,J){return T(N$(g($),{environment:J.environment,cwd:Z,originalCwd:J.originalCwd,strict:J.strict,paranoid:J.paranoidRm,allowTmpdirVar:J.allowTmpdirVar,tmpdirWordSplittingUnsafe:a1(J.envAssignments??new Map,J.environment),trustedTmpdirValue:G0(J.envAssignments??new Map,J.environment),protectedGitMetadata:J.protectedGitMetadata,policy:J.policy}),J.policy)}function N9($){return{childAnalyses:$.length,derivedTokens:$.length,derivedBytes:b$($)}}function e5($){return WJ([$])}function WJ($){return{childAnalyses:1,derivedTokens:$.length,derivedBytes:b$($)}}function $J($,Z){if(Z.length>E.maxChildAnalyses)return{childAnalyses:Z.length};return{childAnalyses:Z.length,derivedTokens:t(Z.map((J)=>$.length+J.length),E.maxDerivedTokens),derivedBytes:t([j1(b$($),Z.length,E.maxDerivedBytes),t(Z.map((J)=>b$(J)),E.maxDerivedBytes)],E.maxDerivedBytes)}}function ZJ($,Z){return K3([$],Z,"generic")}function K3($,Z,J){if(Z.length>E.maxChildAnalyses)return{childAnalyses:Z.length};let Q=j1($.length,Z.length,E.maxDerivedTokens);if(Q>E.maxDerivedTokens)return{childAnalyses:Z.length,derivedTokens:Q};let X=GJ($.map((W)=>UJ(W,J))),K=j1(X.occurrences,Z.length,E.maxPlaceholderReplacements);if(K>E.maxPlaceholderReplacements)return{childAnalyses:Z.length,derivedTokens:Q,placeholderReplacements:K};if(qJ(X,Z,K))return{childAnalyses:Z.length,derivedTokens:Q,derivedBytes:E.maxDerivedBytes+1,placeholderReplacements:K};let Y=J==="generic"?Z0:R9,B=t(Z.map((W)=>b$($.map((q)=>Y(q,W)))),E.maxDerivedBytes);return{childAnalyses:Z.length,derivedTokens:Q,derivedBytes:B,placeholderReplacements:K}}function qJ($,Z,J){let Q=E.maxDerivedBytes+4*J;return t([j1($.fixedBytes,Z.length,Q),j1($.occurrences,t(Z.map((X)=>X.reduce((K,Y)=>Math.max(K,z$(Y)),0)),Q),Q)],Q)>Q}function eH($,Z){let J=$.filter((U)=>U.hasPlaceholder),Q=Math.max(Z.length,1),X=t(J.map((U)=>U.frequency),E.maxChildAnalyses),K=j1(X,Q,E.maxChildAnalyses),Y=j1(X,Q,E.maxDerivedTokens);if(K>E.maxChildAnalyses||Y>E.maxDerivedTokens)return{childAnalyses:K,derivedTokens:Y};if(Z.length===0)return{childAnalyses:K,derivedTokens:Y,derivedBytes:t(J.map((U)=>j1(z$(U.value),U.frequency,E.maxDerivedBytes)),E.maxDerivedBytes)};let B=GJ(J.map((U)=>Zj(UJ(U.value,"generic"),U.frequency))),W=j1(B.occurrences,Q,E.maxPlaceholderReplacements);if(W>E.maxPlaceholderReplacements)return{childAnalyses:K,placeholderReplacements:W};if(qJ(B,Z,W))return{childAnalyses:K,derivedTokens:Y,derivedBytes:E.maxDerivedBytes+1,placeholderReplacements:W};let q=t(J.map((U)=>j1(b$(Z.map((H)=>Z0(U.value,H))),U.frequency,E.maxDerivedBytes)),E.maxDerivedBytes);return{childAnalyses:K,derivedTokens:Y,derivedBytes:q,placeholderReplacements:W}}function $j($,Z){return{childAnalyses:t([$.childAnalyses??0,Z.childAnalyses??0],E.maxChildAnalyses),derivedTokens:t([$.derivedTokens??0,Z.derivedTokens??0],E.maxDerivedTokens),derivedBytes:t([$.derivedBytes??0,Z.derivedBytes??0],E.maxDerivedBytes),placeholderReplacements:t([$.placeholderReplacements??0,Z.placeholderReplacements??0],E.maxPlaceholderReplacements)}}function UJ($,Z){let J=Z==="generic"?$.matchAll(/\{[^{}\s]*\}/g):$.matchAll(QJ),Q=0,X=0,K=0;for(let Y of J){if(Q>=E.maxPlaceholderReplacements)return{occurrences:E.maxPlaceholderReplacements+1,fixedBytes:0};X=t([X,z$($.slice(K,Y.index))],Y3),Q++,K=Y.index+Y[0].length}return{occurrences:Q,fixedBytes:Q===0?z$($):t([X,z$($.slice(K))],Y3)}}function Zj($,Z){return{occurrences:j1($.occurrences,Z,E.maxPlaceholderReplacements),fixedBytes:j1($.fixedBytes,Z,Y3)}}function GJ($){return{occurrences:t($.map((Z)=>Z.occurrences),E.maxPlaceholderReplacements),fixedBytes:t($.map((Z)=>Z.fixedBytes),Y3)}}function b$($,Z=E.maxDerivedBytes){return t($.map(z$),Z)}function z$($){return cH.encode($).byteLength}function t($,Z){let J=0;for(let Q of $){if(!Number.isSafeInteger(Q)||Q<0||Q>Z-J)return Z+1;J+=Q}return J}function j1($,Z,J){if(!Number.isSafeInteger($)||!Number.isSafeInteger(Z)||$<0||Z<0||$!==0&&Z>Math.floor(J/$))return J+1;return $*Z}function V9($,Z,J){let Q=[];for(let X of $){let K=J.get(X)??Z?.get(X);if(K!==void 0)Q.push(K)}return Q.push(...J.values()),Jj(Q)}function Jj($){let Z=new Map;for(let Q of $)Z.set(Q,(Z.get(Q)??0)+1);let J=[...Z].map(([Q,X])=>({value:Q,frequency:X,hasPlaceholder:l(Q)}));return{values:$,entries:J,byValue:new Map(J.map((Q)=>[Q.value,Q]))}}function JJ($,Z,J,Q){return q1($.values,(X)=>{if(!$.byValue.get(X)?.hasPlaceholder)return null;let K=Z.length>0?Z:[void 0];return q1(K,(Y)=>{let B=Y===void 0?X:Z0(X,Y);return J.analyzeNested(B,{envAssignments:J.envAssignments,effectiveCwd:Q?null:J.cwd})})})}function HJ($,Z,J){let Q={};if($)Q.envAssignments=$;if(J)return Q.effectiveCwd=null,Q.worktreeMode=!1,Q;if(Z!==void 0)Q.effectiveCwd=Z;return Object.keys(Q).length>0?Q:void 0}function Z0($,Z){return $.replace(/\{[^{}\s]*\}/g,(J)=>jJ(J,Z))}function R9($,Z){return $.replace(QJ,(J)=>jJ(J,Z))}function jJ($,Z){let J=/^\{(-?\d+)[^{}\s]*\}$/.exec($)?.[1];if(J===void 0)return Z[0]??"";let Q=Number(J),X=Q>0?Q-1:Z.length+Q;return Z[X]??""}function l($){return hH.test($)}function _J($){if(z9($))return!0;for(let Z of $.matchAll(/\{[^{}\s]*\}/g))if(!/^(?:\{\}|\{-?\d+\})$/.test(Z[0]))return!0;return!1}function z9($){let Z=$.indexOf("{=");return Z!==-1&&$.indexOf("=}",Z+2)!==-1}function OJ($){return/^\{[^{}\s]*\}$/.test($)}function LJ($){let Z=1,J=[],Q=$.length,X=-1,K=!1,Y=!1,B=!1,W,q=$.some((O)=>O==="::::"||O==="::::+"||O===":::+"),U=[];while(Z<$.length){let O=$[Z];if(O===void 0)break;if(O===":::"){X=Z;break}if(O==="--"){let f=e6($,Z+1);J.push(...f.templateTokens),Q=Z+1,X=f.markerIndex;break}if(!O.startsWith("-")){let f=e6($,Z);J.push(...f.templateTokens),Q=Z,X=f.markerIndex;break}let M=$[Z+1],L=O.indexOf("="),D=L===-1?O:O.slice(0,L),z=L===-1?void 0:O.slice(L+1);if(O==="--dry-run"){B=!0,Z++;continue}if(O==="-I"||O.startsWith("-I")&&O.length>2){q||=(O==="-I"?M:O.slice(2))!=="{}",Z+=O==="-I"?2:1;continue}if(O==="--replace"||O==="-i"){q=!0,Z+=2;continue}if(D==="--replace"||O.startsWith("-i")&&O.length>2){let f=D==="--replace"?z:O.slice(2);q||=f!==""&&f!=="{}",Z++;continue}if(O==="-a"||mH.has(D)){q=!0,Z+=z===void 0?2:1;continue}if(O==="--pipe"||O==="--pipepart"){Y=!0,Z++;continue}if(D==="--env"){U.push(...Kj(z??M)),Z+=z===void 0?2:1;continue}if(n5.has(D)||O.startsWith("-S")&&O.length>2){K=!0,Z+=n5.has(O)?2:1;continue}if(pH.has(D)){let f=z??M;if(f===void 0||f===":::"||f==="--"){q=!0,Z++;continue}W=f,q||=z!==void 0&&f==="",Z+=z===void 0?2:1;continue}if(O.startsWith("-j")&&O.length>2&&/^\d+$/.test(O.slice(2))){Z++;continue}if(O.startsWith("--")&&z!==void 0){Z++;continue}if(lH.has(O)){if(M===void 0||M===":::"||M==="--"){q=!0,Z++;continue}Z+=2;continue}Z+=O==="-j"||O==="--jobs"?2:1}q||=J.some(B?z9:_J);let H=[];if(X!==-1){let O=[];for(let M=X+1;M<$.length;M++){let L=$[M];if(L===":::"){H.push(O),O=[];continue}if(L!==void 0)O.push(L)}H.push(O)}let j=Xj(H),G=J.some(l),_=J.length===0&&X===-1;return{template:J,jobs:j,childStart:Q,templateHasPlaceholder:G,runsRemotely:K,usesStdin:Y||X===-1,envNames:U,readsCommandsFromInput:_,unsupported:q,workdir:W,dryRun:B}}function Qj($,Z,J){if($===void 0)return;if($==="..."||/[{}$`*?~[]/.test($))return null;if(!Z&&!wH($))return null;try{return b0(Z??$,$,J)}catch{return null}}function Xj($){if($.length===0||$.some((J)=>J.length===0))return[];let Z=[[]];for(let J of $){if(J.length===1){let X=J[0];if(X===void 0)return[];for(let K of Z)K.push(X);continue}let Q=[];for(let X of Z)for(let K of J)if(Q.push([...X,K]),Q.length>E.maxChildAnalyses)return Q;Z=Q}return Z}function Kj($){return($??"").split(",").map((Z)=>Z.trim()).filter(Boolean)}function MJ($){return LJ($).childStart}var Yj="dynamic command name contains shell substitution output and cannot be verified safely. Use a literal executable name.",b9="shell substitution output can change guarded command structure and cannot be verified safely. Use literal subcommands and options.",Bj=new Set(["branch","checkout","clean","merge","push","rebase","reflog","reset","restore","stash","switch","tag","worktree"]);function f9($){return $?.parts.some((Z)=>Z.provenance==="command-substitution")??!1}function I9($){return $?.parts.some((Z)=>Z.provenance==="literal"&&Z.raw.replace(/^["']/,"").startsWith("-"))??!1}function NJ($,Z,J,Q=!1,X){let K=F6($,Z)&&a(X,"shell.dynamic-executable",Q)?N("shell.dynamic-executable",Yj):null;return T(K,X)??VJ($,Z,J,Q,X)}function VJ($,Z,J,Q,X){if(Z.length<2)return null;let K=Z.flatMap((B,W)=>f9(B)?[W]:[]);if(K.length===0)return null;let Y=x(Z[0]?.text??"");if(Y==="git"){let B=G$($,Z),W=qj(B);if(a(X,"shell.dynamic-structure",Q)&&K.some((H)=>H<=W))return T(N("shell.dynamic-structure",b9),X);if(T(F$(B,{env:J.env}),X))return null;let q=Z[W]?.text.toLowerCase(),U=B.findIndex((H,j)=>j>W&&S(H)==="--");if(a(X,"shell.dynamic-structure",Q)&&q&&Bj.has(q)&&K.some((H)=>H>W&&(U===-1||H<U)))return T(N("shell.dynamic-structure",b9),X);return null}if(Y==="find")return a(X,"shell.dynamic-structure",Q)&&Uj(Z)?T(N("shell.dynamic-structure",b9),X):null;if(Y==="xargs")return FJ($,Z.slice(i0(Z.map(S)).childStart),"xargs",J,Q,X);if(Y==="parallel")return FJ($,Z.slice(MJ(Z.map(S))),"parallel",J,Q,X);return null}function FJ($,Z,J,Q,X,K){if(Z.length===0)return null;let Y=Wj(Z,Q);if(F6($,Y)){let W=T(N(`${J}.shell-dynamic`,J==="xargs"?L9:V2),K);if(W)return W}let B=VJ($,Y,Q,X,K);if(B)return B;if(Y[0]?.text==="rm"&&Y.slice(1).some((W)=>f9(W)&&I9(W)))return T(N(`${J}.rm-recursive-force-dynamic`,J==="xargs"?O9:N2),K);return null}function Wj($,Z){let J=u0($,Z),Q=J.rewritten?g(J.words.map(S)):J.words,X=Q[0];return X&&S(X)==="busybox"?Q.slice(1):Q}function qj($){let Z=1;while(Z<$.length){let J=$[Z],Q=J?S(J):"";if(i1.has(Q)){Z+=2;continue}if(Q.startsWith("-")){Z++;continue}return Z}return Z}function Uj($){let Z=!1,J=0,Q=!1,X=!1;for(let K=1;K<$.length;K++){let Y=$[K];if(!Y)continue;let B=f9(Y);if(J>0){J--;continue}if(X){if(Y.text===";"||Y.text==="+"){X=!1,Z=!0,Q=!1;continue}if(B&&(Q||I9(Y)))return!0;Q=!1;continue}if(!Z&&!Y.text.startsWith("-")){if(B&&(K>1||I9(Y)))return!0;continue}if(Z=!0,B)return!0;let W=I0(Y.text);if(W>0){J=W;continue}if(j0(Y.text))X=!0,Q=!0}return!1}function P9($,Z){return $.some((J)=>{if(J.value==="-"&&(J.kind==="main-script"||J.kind==="program-file"))return!0;return!I4(Z[J.tokenIndex],J.value)})}var Gj="dd writing to a /dev device can destroy a disk or partition. Run device writes manually after confirming the target.",Hj="mkfs formatting a /dev device erases everything on it. Run the format manually after confirming the target.",jj="shred permanently destroys the given target. Use rm for ordinary deletes, or run shred manually.";function RJ($,Z){let J=Z.slice(1);if($==="dd"&&J.some((Q)=>/^of=\/dev\/.+/.test(Q)))return N("dd.device-write",Gj);if(($==="mkfs"||$.startsWith("mkfs."))&&J.some((Q)=>Q.startsWith("/dev/")))return N("mkfs.device",Hj);if($==="shred"&&J.length>0)return N("shred.target",jj);return null}var zJ=[{heads:new Set(["rm","rmdir"]),analyze:($)=>N$($.words,{environment:$.options.environment,cwd:$.cwd,originalCwd:$.originalCwd,strict:$.options.strict,paranoid:$.options.paranoidRm,allowTmpdirVar:$.allowTmpdirVar,tmpdirWordSplittingUnsafe:a1($.envAssignments,$.options.environment),trustedTmpdirValue:G0($.envAssignments,$.options.environment),protectedGitMetadata:$.options.protectedGitMetadata,policy:$.options.policy})},{heads:new Set(["git"]),analyze:($)=>F$($.words,C9($))},{heads:new Set(["find"]),analyze:($)=>t4($.words,{environment:$.options.environment,cwd:$.cwd,originalCwd:$.originalCwd,strict:$.options.strict,allowTmpdirVar:$.allowTmpdirVar,tmpdirWordSplittingUnsafe:a1($.envAssignments,$.options.environment),trustedTmpdirValue:G0($.envAssignments,$.options.environment),protectedGitMetadata:$.options.protectedGitMetadata,derivedCommandWorkBudget:$.options.derivedCommandWorkBudget,envAssignments:$.envAssignments,policy:$.options.policy,analyzeTokens:$.analyzeChildTokens,analyzeNested:(Z,J)=>n0($.options.analyzeNested(Z,J))})},{heads:new Set(["xargs"]),analyze:($)=>c5($.words,{...DJ($),analyzeNested:(Z,J)=>n0($.options.analyzeNested(Z,J))})},{heads:new Set(["parallel"]),analyze:($)=>XJ($.words,{...DJ($),budget:$.options.parallelBudget,analyzeNested:(Z,J)=>n0($.options.analyzeNested(Z,J))})}];function DJ($){return{environment:$.options.environment,cwd:$.cwd,originalCwd:$.originalCwd,strict:$.options.strict,paranoidRm:$.options.paranoidRm,paranoidInterpreters:$.options.paranoidInterpreters,allowTmpdirVar:$.allowTmpdirVar,protectedGitMetadata:$.options.protectedGitMetadata,derivedCommandWorkBudget:$.options.derivedCommandWorkBudget,envAssignments:$.envAssignments,worktreeMode:$.options.worktreeMode,policy:$.options.policy,scanWork:$.options.scanWork}}function n0($){return $?{id:$.ruleId??"",reason:$.reason,intent:$.intent??"manual_only"}:null}function C9($){return{env:$.options.environment.env,cwd:$.cwd,dynamicArguments:$.dynamicArguments,envAssignments:$.envAssignments,policy:$.options.policy,worktreeMode:$.options.worktreeMode}}var PJ="shell execution source cannot be verified safely. Use a literal command string or ask the user to run it manually.";function CJ($){return zJ.find((Z)=>Z.heads.has($))?.analyze}function R2($,Z,J){let Q=J.trace;if($.length===0)return null;let X=J.commandView?.dialect??"posix",K=(P)=>P.map((v)=>X==="posix"?S(v):v.text),Y=J.effectiveCwd===null,B=Y?void 0:J.effectiveCwd??J.cwd,W=Y?void 0:J.cwd,q=f4($);if(q.envAssignments.size>0)Q?.recordSegment({type:"env-strip",input:K($),envVars:Object.fromEntries([...q.envAssignments.keys()].map((P)=>[P,"<redacted>"])),output:K(q.words)});let U=u0(q.words,J.environment,B,new Map([...J.envAssignments??[],...q.envAssignments]));if(U.unverifiableEnvSplit)throw new l0;let H=U.rewritten?g(K(U.words)):G$(X,U.words),j=K(H),G={...J,wrapperNormalizationBudget:J.wrapperNormalizationBudget??{iterations:0}};if(Q&&q.words.length>H.length){let P=K(q.words);Q.recordSegment({type:"leading-tokens-stripped",input:P,removed:P.slice(0,P.length-H.length),output:j})}let _=new Map([...J.envAssignments??[],...q.envAssignments,...U.envAssignments]),O=j[0];if(!O)return null;if(B2(O))throw new P1;let M=x(O),L=U.cwd===null?void 0:U.cwd??B,D=U.cwd===null?void 0:W,z=U.cwd===void 0?J.effectiveCwd:U.cwd,f=!G2(_,J.environment),A=NJ(X,U.words,J.environment,J.strict,J.policy);if(A)return Q?.recordSegment({type:"rule-check",ruleModule:"analyze/segment.ts",ruleFunction:"analyzeDynamicCommandStructure",matched:!0,reason:A.reason}),_0(A);let F=m4(j,J.policy);if(F){for(let P of[F.childIndex,...F.alternativeChildIndices]){bJ(G.wrapperNormalizationBudget);let v=H.slice(P);Q?.recordSegment({type:"transparent-wrapper",wrapper:F.wrapper,output:K(v)});let r=R2(v,Z,{...G,effectiveCwd:z,envAssignments:_});if(r)return r}return null}let R=M==="eval"?V$(H):M==="trap"?h5(H):void 0;if(R?.kind==="dynamic")return A1(Q);if(R?.kind==="literal"){Q?.recordSegment({type:"recurse",reason:M==="eval"?"shell-eval":"shell-trap",innerCommand:R.source,depth:Z+1});let P=J.analyzeNested(R.source,{effectiveCwd:z,envAssignments:_,functionDefinitions:J.functionDefinitions});if(P)return P}if(EJ(O,M)){if(C1(j))return null;let P=_j(j,_,z,J,Q,Z);if(P)return P;let v=o1(j);if(v){let e0=Z3(H,v);if(e0.kind==="dynamic")return A1(Q);let S3=e0.kind==="literal"?e0.source:v,JZ=Oj(S3);Q?.recordSegment({type:"shell-wrapper",wrapper:M,innerCommand:JZ}),Q?.recordSegment({type:"recurse",reason:"shell-wrapper",innerCommand:JZ,depth:Z+1});let QZ=J.analyzeNested(S3,{effectiveCwd:z,envAssignments:_});if(QZ)return QZ;return R$(S3)?A1(Q):null}let r=e1(H);if(r.kind==="dynamic")return A1(Q);if(r.kind==="literal")return U3(r.source,z,_,J,Q,Z);let Z1=g5(H,J.commandView?.redirections??[],J.hasPipelineInput??!1,J.literalShellInput);if(Z1.kind==="dynamic")return A1(Q);if(Z1.kind==="literal")return Q?.recordSegment({type:"recurse",reason:"shell-stdin",innerCommand:Z1.source,depth:Z+1}),J.analyzeNested(Z1.source,{effectiveCwd:z,envAssignments:_})}if(M==="source"||M==="."){let P=j[1]==="-p"?2:null;if(P!==null){let e0=J.commandView?H[P]:void 0;if(!e0)return null;if(e0.provenance!=="literal")return A1(Q)}let v=P===null?1:3,r=j[v]==="--"?v+1:v,Z1=J.commandView?H[r]:void 0;if(!Z1)return null;if(Z1.provenance!=="literal")return A1(Q);return U3(Z1.text,z,_,J,Q,Z)}if(F1.has(M)){if(J.strict&&P9(X2(j),H))return A1(Q);let P=S4(j,(r)=>n0(J.analyzeNested(r,{effectiveCwd:z,envAssignments:_}))),v=T(P,J.policy);if(v)return Q?.recordSegment({type:"rule-check",ruleModule:"awk",ruleFunction:"analyzeAwkSystemCalls",matched:!0,reason:v.reason}),_0(v)}if(N1(M)){if(J.strict&&P9(g4(j),H))return A1(Q);let P=h4(j);if(P){let v=a(J.policy,"interpreter.one-liner-paranoid",!!J.paranoidInterpreters);if(Q?.recordSegment({type:"interpreter",interpreter:M,codeArg:P,paranoidBlocked:v}),v){let Z1=T(N("interpreter.one-liner-paranoid",O$),J.policy);if(Z1)return _0(Z1)}if(x4(M,P))return null;Q?.recordSegment({type:"recurse",reason:"interpreter",innerCommand:P,depth:Z+1});let r=J.analyzeNested(P,{effectiveCwd:z,envAssignments:_});if(r&&r.ruleId!=="raw-text.dangerous-command"&&(r.reason!==V0||U$(P)))return r;if(L$(P,J.scanWork)){let Z1=T(N("interpreter.dangerous-command",k0),J.policy);if(Z1)return Q?.recordSegment({type:"dangerous-text",token:P,matched:!0,reason:k0}),_0(Z1)}Q=void 0}}if(M==="busybox"&&j.length>1)return bJ(G.wrapperNormalizationBudget),Q?.recordSegment({type:"busybox",subcommand:j[1]??"unknown"}),Q?.recordSegment({type:"recurse",reason:"busybox",innerCommand:j.slice(1).join(" "),depth:Z+1}),R2(H.slice(1),Z,{...G,effectiveCwd:z,envAssignments:_});let b=T(RJ(M,j),J.policy);if(b)return Q?.recordSegment({type:"rule-check",ruleModule:"analyze/device.ts",ruleFunction:"analyzeDeviceCommand",matched:!0,reason:b.reason}),_0(b);let I=Q===G.trace?G:{...G,trace:Q},C={words:H,head:M,cwd:L,originalCwd:D,envAssignments:_,allowTmpdirVar:f,dynamicArguments:U.words.some((P)=>P.provenance==="command-substitution"),depth:Z,effectiveCwd:z,options:I,analyzeChildTokens:(P,v)=>n0(R2(g(P),Z+1,{...I,commandView:void 0,effectiveCwd:v,envAssignments:_}))??Q1(P,I.policy.rules)},y=CJ(M);if(M==="rm"||M==="xargs"||M==="parallel")Q?.recordSegment({type:"tmpdir-check",tmpdirValue:_.has("TMPDIR")||J.environment.env.has("TMPDIR")?"<redacted>":null,isOverriddenToNonTemp:!f,allowTmpdirVar:f});let w=Q&&M==="git"?f5(C.words,C9(C)):void 0,k=IJ(w?w.match:y?.(C)??null,J.policy);if(Q)Lj(C,k,w?.relaxation??null);if(k)return _0(k);let B1=y!==void 0;if(!B1)if(!a2.has(M)){let P=Q?[]:void 0;for(let v=1;v<j.length;v++){let r=j[v];if(!r)continue;P?.push(r);let Z1=IJ(Mj(C,j,v),J.policy);if(Z1)return Q?.recordSegment({type:"fallback-scan",tokensScanned:P??[],embeddedCommandFound:x(r)}),_0(Z1)}Q?.recordSegment({type:"fallback-scan",tokensScanned:P??[]})}else Q?.recordSegment({type:"fallback-scan",tokensScanned:[]});else Q?.recordSegment({type:"fallback-scan",tokensScanned:[]});if(Z===0||!B1){let P=Q1(j,J.policy.rules);if(Q?.recordSegment({type:"custom-rules-check",rulesChecked:J.policy.rules.length>0,matched:!!P,reason:P?.reason}),P)return _0(P)}else Q?.recordSegment({type:"custom-rules-check",rulesChecked:!1,matched:!1});return null}function _j($,Z,J,Q,X,K){let Y=S5($);if(Y.argvSource?.kind==="absent")return A1(X);if(Y.argvSourceApplies&&Y.argvSource){let W=U3(Y.argvSource.value,J,Z,Q,X,K,!0);if(W)return W}if(!Y.envSourceApplies||!Y.envName)return null;let B=Z.get(Y.envName);if(!B)return null;return U3(B,J,Z,Q,X,K,!0)}function U3($,Z,J,Q,X,K,Y=!1){if(Y&&/[$`*?[\]]/.test($))return A1(X);let B=U2($,Z,Q.environment.paths),W=B?Q.literalHeredocFiles?.get(B):void 0;if(W===void 0)return Y?A1(X):null;return n1(Q.derivedCommandWorkBudget,1),X?.recordSegment({type:"recurse",reason:"heredoc-file",innerCommand:W,depth:K+1}),Q.analyzeNested(W,{effectiveCwd:Z,envAssignments:J})}function Oj($){let Z=$[0];return $.length>=2&&(Z==='"'||Z==="'")&&$.at(-1)===Z?$.slice(1,-1):$}function Lj($,Z,J){let Q={git:["git","analyzeGit"],rm:["analyze/rm.ts","analyzeRm"],find:["analyze/find.ts","analyzeFind"],xargs:["analyze/xargs.ts","analyzeXargs"],parallel:["analyze/parallel.ts","analyzeParallel"]}[$.head];if(!Q)return;if($.options.trace?.recordSegment({type:"rule-check",ruleModule:Q[0]??"",ruleFunction:Q[1]??"",matched:!!Z||!!J,reason:Z?.reason??J?.originalReason}),J)$.options.trace?.recordSegment({type:"worktree-relaxation",originalReason:J.originalReason,gitCwd:J.gitCwd})}function bJ($){if($.iterations>=K$)throw new P1;$.iterations++}function _0($){return{reason:$.reason,ruleId:$.id||void 0,intent:$.intent}}function A1($){return $?.recordSegment({type:"error",message:PJ}),_0(AJ())}function AJ(){return{id:"",reason:PJ,intent:"stop_and_explain"}}function EJ($,Z){return $1.has(Z)||$==="$SHELL"||$==="${SHELL}"||$1.has(h(Z))}function Mj($,Z,J){let Q=k1(Z.slice(J),{environment:$.options.environment,cwd:$.cwd,envAssignments:$.envAssignments,policy:$.options.policy});for(let X of Q){let K=Fj($,J,X);if(K)return K}return null}function Fj($,Z,J){let Q=J.tokens[0];if(!Q)return null;let X=x(Q);if(EJ(Q,X)){n1($.options.derivedCommandWorkBudget,$.words.length-Z);let W=J.tokens;if(C1(W))return null;let q=o1(W);if(!q){if(e1(g(W)).kind==="dynamic")return AJ();return q3($,J)}let U=$.options.analyzeNested(q,{effectiveCwd:J.wrapperCwd===void 0?$.effectiveCwd:J.wrapperCwd,envAssignments:J.envAssignments});return U?n0(U):q3($,J)}let K=CJ(X);if(!K||X==="xargs"||X==="parallel"){if(J.wrappedByTransparent&&$.options.policy.rules.length>0)n1($.options.derivedCommandWorkBudget,$.words.length-Z);return q3($,J)}n1($.options.derivedCommandWorkBudget,$.words.length-Z);let Y=[X,...J.tokens.slice(1)],B={...$,words:g(Y),head:X,cwd:J.cwd,originalCwd:J.wrapperCwd===null?void 0:$.originalCwd,envAssignments:J.envAssignments,allowTmpdirVar:!G2(J.envAssignments,$.options.environment),effectiveCwd:J.wrapperCwd===void 0?$.effectiveCwd:J.wrapperCwd,options:X==="git"?{...$.options,worktreeMode:!1}:$.options};return K(B)??q3($,J)}function q3($,Z){return Z.wrappedByTransparent?Q1(Z.tokens,$.options.policy.rules):null}function IJ($,Z){return $?.id.startsWith("custom.")?$:T($,Z)}var Nj=/^\s*(?:\$\(\s*)?[({]*\s*(?:command\s+|builtin\s+)?(?:cd|pushd|popd)(?:\s|$)/,Vj=new Set(["cd","chdir","pop-location","popd","push-location","pushd","set-location","sl"]);function Rj($,Z){let J=yJ($,Z);if(J.length===0)return!1;let Q=J[SJ(J)];if(Q==="cd"||Q==="pushd"||Q==="popd")return!0;return Nj.test($.join(" "))}function TJ($,Z,J,Q){if($.dialect==="powershell"){let B=Dj($.words,Q);if(B.kind==="none")return;if(!Z||B.kind==="unknown")return null;return fJ(fj(B.target),Z,J.paths)}let X=$.words.map(S);if(!Rj(X,J))return;if(!Z)return null;let K=yJ(X,J,Z),Y=SJ(K);if(Y===-1||K[Y]!=="cd")return null;return fJ(K[Y+1],Z,J.paths)}function fJ($,Z,J){if(!$||$==="-"||$.includes("$")||$.includes("`"))return null;try{return Pj(b0(Z,$,J),Z,J)?Z:null}catch{return null}}function Dj($,Z){let J=zj($[0])?1:0,Q=$[J];if(!bj(Q,J===1))return{kind:"none"};let X=Q.text.toLowerCase(),K=X.split(/[\\/]/).pop()??X;if(!Vj.has(K))return{kind:"none"};if(X!==K||K==="pop-location"||K==="popd")return{kind:"unknown"};return Ij($.slice(J+1),Z)}function zj($){return $?.provenance==="literal"&&!$.quoted&&$.raw===$.text&&($.text==="&"||$.text===".")}function bj($,Z){return $?.provenance==="literal"&&(Z||!$.quoted&&$.raw===$.text)}function Ij($,Z){let J;for(let Q of $){if(Q.provenance!=="literal"||J!==void 0)return{kind:"unknown"};J=Q.text}if(J!==void 0)return{kind:"target",target:J};return Z===void 0?{kind:"unknown"}:{kind:"target",target:Z}}function fj($){return $.includes("::")?void 0:$.replaceAll("\\","/")}function SJ($){let Z=0;if($[0]==="builtin"&&$.length>1)Z=1;if($[Z]!=="time")return Z;let J=Z+1;while($[J]?.startsWith("-"))J++;return J}function yJ($,Z,J){let Q=Cj($);return I1([...Q],Z,J)}function Pj($,Z,J){let Q=J.realpath($),X=J.realpath(Z);if(Q===null||X===null)return W3($)===W3(Z);return W3(Q)===W3(X)}function Cj($){let Z=0;while(Z<$.length){let J=$[Z];if(J==="{"||J==="("||J==="$(")Z++;else break}return $.slice(Z)}var D2="TMPDIR",z2="IFS",Aj=/^([A-Za-z_][A-Za-z0-9_]*)\+=/,A9=/^[A-Za-z_][A-Za-z0-9_]*$/;function vJ($,Z){let J=wj($,Z);return{env:$,effectiveEnvAssignments:J,shellAssignments:new Map,exportedNames:vj($,J),allexport:!1,keywordExport:!1}}function uJ($){return{env:$.env,effectiveEnvAssignments:$.effectiveEnvAssignments?new Map($.effectiveEnvAssignments):void 0,shellAssignments:new Map($.shellAssignments),exportedNames:new Set($.exportedNames),allexport:$.allexport,keywordExport:$.keywordExport}}function hJ($,Z){let J=Ej($,Z);if(!J)return;let{command:Q,commandIndex:X,leadingAssignments:K,prefixAssignmentsPersist:Y}=J;if(Q===null){for(let W of K.values())wJ(Z,W);return}if(Y)for(let W of K.values())Z.shellAssignments.set(W.name,W.value),Z.exportedNames.add(W.name),C0(Z,W);if(Q==="set"){let W=mj($,X);if(W.allexport!==null)Z.allexport=W.allexport;if(W.keywordExport!==null)Z.keywordExport=W.keywordExport;return}if(Q==="unset"){let W=kj($,X);if(W===null)return;for(let q of $.slice(W))gj(Z,q);return}if(Q!=="export"&&Q!=="typeset"&&Q!=="declare"&&Q!=="readonly")return;for(let W of K.values())wJ(Z,W);if(Q==="export"){let W=xj($,X);if(W===null)return;for(let q of $.slice(W))uj(Z,q);return}let B=lj($,X);if(B===null)return;for(let W of $.slice(B.operandsStart))hj(Z,W,B.exports,Q==="readonly"?K:void 0)}function gJ($,Z){if(!Z.keywordExport)return Z.effectiveEnvAssignments;let J=null,Q=j3(Z);for(let X of $){let K=H3(X,Q,Z.env);if(!K)continue;J??=new Map(Z.effectiveEnvAssignments??[]),J.set(K.name,K.value),Q.set(K.name,K.value)}return J??Z.effectiveEnvAssignments}function Ej($,Z){let J=new Map,Q=0;while(Q<$.length){let B=$[Q];if(!B)return null;let W=H3(B,j3(Z,J),Z.env);if(!W)break;J.set(W.name,W),Q++}if(Q>=$.length)return{command:null,commandIndex:Q,leadingAssignments:J,prefixAssignmentsPersist:!1};let X=Q,K=Q,Y=$[K]??null;while(Y==="builtin"||Y==="command"||Y==="time"){if(Y==="builtin"){if(K++,$[K]==="--")K++;Y=$[K]??null;continue}if(Y==="command"){let W=Tj($,K);if(!W)return null;K=W.commandIndex,Y=W.command;continue}let B=Sj($,K);if(!B)return null;K=B.commandIndex,Y=B.command}if(Y===null)return null;return{command:Y,commandIndex:K,leadingAssignments:J,prefixAssignmentsPersist:K===X&&(Y==="unset"||Y==="set"||Y==="export"||Y==="readonly")}}function Tj($,Z){return kJ($,Z,(J)=>{if(J==="-p")return"skip";return J==="-v"||J==="-V"?"abort":"stop"})}function Sj($,Z){return kJ($,Z,(J)=>J.startsWith("-")?"skip":"stop")}function kJ($,Z,J){let Q=Z+1;while(Q<$.length){let K=$[Q];if(!K)return null;if(K==="--"){Q++;break}let Y=J(K);if(Y==="abort")return null;if(Y==="skip"){Q++;continue}break}let X=$[Q];return X?{command:X,commandIndex:Q}:null}function H3($,Z,J){return s1($)??yj($,Z,J)}function yj($,Z,J){let Q=R4($,J,Z);if(Q)return Q;let X=$.match(Aj)?.[1];if(!X)return null;let K=$.indexOf("=");return{name:X,value:`${Z.has(X)?Z.get(X):J.get(X)??""}${$.slice(K+1)}`}}function G3($){return $===D2||$===z2||I6($)}function j3($,Z){return new Map([...$.effectiveEnvAssignments??[],...$.shellAssignments,...[...Z?.values()??[]].map((J)=>[J.name,J.value])])}function wj($,Z){let J=[...N4,D2,z2].map((Q)=>{let X=$.get(Q);return X===void 0?null:[Q,X]}).filter((Q)=>Q!==null);if(J.length===0)return Z;return new Map([...J,...Z??[]])}function vj($,Z){let J=new Set;for(let Q of $.keys())if(G3(Q))J.add(Q);for(let Q of Z?.keys()??[])if(G3(Q))J.add(Q);return J}function wJ($,Z){if($.shellAssignments.set(Z.name,Z.value),Z.name===D2||Z.name===z2||$.allexport||$.exportedNames.has(Z.name))C0($,Z)}function C0($,Z){let J=new Map($.effectiveEnvAssignments??[]);J.set(Z.name,Z.value),$.effectiveEnvAssignments=J}function uj($,Z){let J=H3(Z,j3($),$.env);if(J){$.shellAssignments.set(J.name,J.value),$.exportedNames.add(J.name),C0($,J);return}if(A9.test(Z))xJ($,Z)}function hj($,Z,J,Q){let X=H3(Z,j3($),$.env);if(X){if($.shellAssignments.set(X.name,X.value),J)$.exportedNames.add(X.name),C0($,X);else if(X.name===D2||X.name===z2||$.allexport||$.exportedNames.has(X.name))C0($,X);return}let K=Q?.get(Z);if(K){$.exportedNames.add(Z),C0($,K);return}if(J&&A9.test(Z))xJ($,Z)}function xJ($,Z){$.exportedNames.add(Z),C0($,{name:Z,value:$.shellAssignments.get(Z)??$.effectiveEnvAssignments?.get(Z)??$.env.get(Z)??""})}function gj($,Z){if(!G3(Z)&&!A9.test(Z))return;if($.shellAssignments.set(Z,""),$.exportedNames.delete(Z),!G3(Z)||Z===D2||Z===z2||a$(Z)){C0($,{name:Z,value:""});return}if(!$.effectiveEnvAssignments?.has(Z))return;let J=new Map($.effectiveEnvAssignments);J.delete(Z),$.effectiveEnvAssignments=J.size===0?void 0:J}function kj($,Z){return lJ($,Z,(J)=>J==="-v")}function xj($,Z){return lJ($,Z,(J)=>J==="-p")}function lJ($,Z,J){let Q=Z+1;while(Q<$.length){let X=$[Q];if(!X)return null;if(X==="--")return Q+1;if(J(X)){Q++;continue}if(X.startsWith("-"))return null;return Q}return Q}function lj($,Z){let J=Z+1,Q=!1;while(J<$.length){let X=$[J];if(!X)return null;if(X==="--")return{operandsStart:J+1,exports:Q};if(X.startsWith("-")){if(X.slice(1).includes("x"))Q=!0;J++;continue}if(X.startsWith("+")){if(X.slice(1).includes("x"))Q=!1;J++;continue}return{operandsStart:J,exports:Q}}return{operandsStart:J,exports:Q}}function mj($,Z){let J={allexport:null,keywordExport:null},Q=Z+1;while(Q<$.length){let X=$[Q];if(!X)return J;if(X==="--")return J;if(X==="-o"||X==="+o"){if($[Q+1]==="allexport")J.allexport=X==="-o";if($[Q+1]==="keyword")J.keywordExport=X==="-o";Q+=2;continue}if(X.startsWith("-")&&X.length>1){let K=X.slice(1);if(K.includes("a"))J.allexport=!0;if(K.includes("k"))J.keywordExport=!0;Q++;continue}if(X.startsWith("+")&&X.length>1){let K=X.slice(1);if(K.includes("a"))J.allexport=!1;if(K.includes("k"))J.keywordExport=!1;Q++;continue}return J}return J}var pj="Unquoted heredoc input is not supported safely. Quote the delimiter or ask the user to verify.",a0="This heredoc form or stdin consumer is not supported safely. Use a quoted heredoc with a supported consumer (cat, tee, git apply, git commit, gh pr create, gh issue create), or ask the user to verify.",cj=64;function w9($,Z,J,Q){let X=J.derivedCommandWorkBudget===void 0,K=J.parallelBudget===void 0;try{return dj($,Z,{...J,derivedCommandWorkBudget:J.derivedCommandWorkBudget??d4(),parallelBudget:J.parallelBudget??m7()},Q)}catch(Y){let B=Y instanceof l0?h7:Y instanceof P1&&X?u7:Y instanceof s4&&K?l7:void 0;if(!B)throw Y;if(J.trace?.currentSegmentIndex!==void 0)J.trace.recordSegment({type:"error",message:B});else J.trace?.recordGlobal({type:"error",message:B});return{reason:B,segment:$,intent:"stop_and_explain"}}}function dj($,Z,J,Q){if(Z>=n2)return J.trace?.recordSegment({type:"error",message:Y0}),{reason:Y0,segment:$,intent:"stop_and_explain"};let X=Q??J.factStore?.getCommandProgram($,J.shell??"auto")??w1($,J.shell);if(X.status==="limited")return J.trace?.recordSegment({type:"error",message:Y0}),{reason:Y0,segment:$,intent:"stop_and_explain"};if(X.status==="invalid"){let q=X.issues.find((U)=>U.code.includes("heredoc"));if(q){if(!J.strict)return y9($,J);let U=`Unsupported heredoc syntax: ${q.message}`;return J.trace?.recordGlobal({type:"error",message:U}),{reason:U,segment:$,intent:"stop_and_explain"}}return sJ($,J),{reason:V0,segment:$,intent:"stop_and_explain"}}if(J.strict&&X.status==="partial")return sJ($,J),{reason:V0,segment:$,intent:"stop_and_explain"};if(X.issues.some((q)=>q.code.includes("quote"))&&!J.analyzePartialProgram)return y9($,J);let Y=J.cwd,B=J.effectiveCwd!==void 0?J.effectiveCwd:J.cwd,W=vJ(J.environment.env,J.envAssignments);return L3(X,Z,{...J,rootProgram:X},Y,[{effectiveCwd:B,shellGitContextState:W,literalHeredocFiles:new Map(J.literalHeredocFiles),functionDefinitions:new Map(J.functionDefinitions)}]).result}function L3($,Z,J,Q,X){let K=[...X],Y,B;for(let[W,q]of $.nodes.entries()){if(q.kind==="connector"){B=q.operator;continue}let U=$.nodes[W+1],H=U?.kind==="connector"?U.operator:void 0,j=ij($,W,q,B,H),G=B==="&&"||B==="||",_=G?Y:void 0,O=B==="&&"?_?.success??K:B==="||"?_?.failure??K:K,M=B==="||"?_?.success??[]:[],L=B==="&&"?_?.failure??[]:[],D=G||I$(H);if(q.kind==="function"){let I=O.flatMap((y)=>{let w=b2(y);return w.functionDefinitions.set(q.name,q.body),E9(y,[w],j,H==="&",I$(H))}),C=T9(I,[],M,L,B,H);K=C.states,Y=C.conditionalStates,B=void 0;continue}if(q.kind==="group"){let I=[],C=[];for(let w of O){let k=L3(q.body,Z,J,Q,[b2(w)]);if(k.result)return k;if(I.push(...E9(w,k.states,j,H==="&",I$(H))),D)C.push(w,...j?k.states.map((B1)=>_3(w,B1)):k.states)}let y=T9(I,C,M,L,B,H);K=y.states,Y=y.conditionalStates,B=void 0;continue}if(q.kind!=="command")continue;let z=J.trace?.flattenNested?J.trace.currentSegmentIndex:J.trace?.allocateSegment(),f=$.nodes[W-2],A=M3(B)&&f?.kind==="command"?u5(f)??rj(f):void 0,F=[],R=[];for(let I of O){let C=nj(q,Z,J,Q,[b2(I)]);if(C.result)return{result:C.result,states:K};let y=$.dialect==="powershell"?C.states:C.states.map((w)=>_3(I,w));for(let w of y){let k=b2(w),B1=tj(q,Z,J.trace?{...J,trace:rJ(J.trace,z)}:J,Q,k,M3(B),A);if(B1)return{result:B1,states:K};let P=G_(q,k.functionDefinitions);if(P)n1(J.derivedCommandWorkBudget,F3(P));let v=P?Z+1>=n2?S9(q.displayText,J,[k]):L3(P,Z+1,J,Q,[k]):{result:null,states:[k]};if(v.result)return v;if(F.push(...E9(I,v.states,j,H==="&",I$(H))),D)R.push(I),R.push(...v.states.map((r)=>j?_3(I,r):r))}}let b=T9(F,R,M,L,B,H);K=b.states,Y=b.conditionalStates,B=void 0}return{result:null,states:K}}function ij($,Z,J,Q,X){if(J.kind==="group"&&J.style==="subshell")return!0;if($.dialect==="posix"&&(M3(Q)||M3(X)))return!0;if(X==="&")return!0;return $.dialect==="powershell"&&J.kind==="group"&&J.style==="brace"&&sj($,Z)}function E9($,Z,J,Q,X){let K=J?Z.map((B)=>_3($,B)):[...Z],Y=X?K.flatMap((B)=>I2($.literalHeredocFiles,B.literalHeredocFiles)?[B]:[{...B,literalHeredocFiles:new Map($.literalHeredocFiles)},B]):K;return Q?[$,...Y]:Y}function _3($,Z){return{...$,literalHeredocFiles:new Map(Z.literalHeredocFiles)}}function sj($,Z){let J=[...$.nodes.slice(0,Z)].reverse().find((X)=>X.kind==="command"||X.kind==="connector");if(!J||J.kind!=="command")return!0;let Q=J.words[0]?.text.toLowerCase();if(Q==="&"||Q===".")return!1;if(Q==="write-output"||Q==="function"||Q==="start-job")return!0;if(aj(J))return!0;return J.source.replaceAll(/\s/g,"").toLowerCase()==="if($false)"}function M3($){return $==="|"||$==="|&"}function rj($){if($?.dialect!=="powershell")return;if($.words.length===1&&$.words[0]?.quoted&&$.words[0].provenance==="literal")return $.words[0].text;if($.words[0]?.text.toLowerCase()==="write-output"&&$.words.length===2&&$.words[1]?.provenance==="literal")return $.words[1].text;return}function I$($){return $==="&&"||$==="||"}function T9($,Z,J,Q,X,K){let Y={success:O3([...J,...$]),failure:O3([...Q,...Z])},B=I$(K)?Y:void 0;return{states:I$(X)||B?O3([...Y.success,...Y.failure]):Y.success,conditionalStates:B}}function rJ($,Z,J=$.flattenNested){return{currentSegmentIndex:Z,flattenNested:J,allocateSegment:$.allocateSegment,getNextSegmentIndex:$.getNextSegmentIndex,recordGlobal:$.recordGlobal,recordSegment:(Q,X=Z)=>$.recordSegment(Q,X)}}function nj($,Z,J,Q,X){let K=$.nested.map((Y)=>({program:Y,depth:Z}));if($.dialect==="powershell"){let Y=oj($);if(Y){if(Z+1>=n2)return S9(Y,J,X);let B=w1(Y,"powershell");if(B.status==="limited")return S9(Y,J,X);if(B.status!=="complete")return mJ(K,J,Q,X);n1(J.derivedCommandWorkBudget,F3(B)),K.push({program:B,depth:Z+1})}}return mJ(K,J,Q,X)}function aj($){let Z=$.words[0];return Z?.provenance==="variable"&&$.words.at(-1)?.text==="="?Z.text.toLowerCase():void 0}function mJ($,Z,J,Q){let X=[...Q];for(let K of $){let Y=[];for(let B of X){let W=L3(K.program,K.depth,Z,J,[b2(B)]);if(W.result)return W;Y.push(...W.states)}X=O3(Y)}return{result:null,states:X}}function oj($){let Z=$.words[0]?.provenance==="literal"&&!$.words[0].quoted&&$.words[0].raw===$.words[0].text&&($.words[0].text==="&"||$.words[0].text==="."),J=Z?1:0,Q=$.words[J];if(Q?.provenance!=="literal"||!Z&&(Q.quoted||Q.raw!==Q.text)||!["iex","invoke-expression"].includes(Q.text.toLowerCase()))return;let X=$.words.slice(J+1),K=X[0]&&!X[0].quoted&&X[0].raw===X[0].text&&["-c","-command"].includes(X[0].text.toLowerCase())?1:0,Y=X[K];return X.length===K+1&&Y?.quoted&&Y.provenance==="literal"?Y.text:void 0}function F3($){return $.nodes.reduce((Z,J)=>Z+(J.kind==="command"?J.words.length+J.nested.reduce((Q,X)=>Q+F3(X),0):J.kind==="group"||J.kind==="function"?F3(J.body):0),0)}function S9($,Z,J){return Z.trace?.recordSegment({type:"error",message:Y0}),{result:{reason:Y0,segment:$,intent:"stop_and_explain"},states:[...J]}}function tj($,Z,J,Q,X,K,Y){let B=K_($);if(B&&J.strict)return J.trace?.recordSegment({type:"error",message:B}),{reason:B,segment:$.source,intent:"stop_and_explain"};nJ($,X,"before-consumer",J.environment.paths);let W=G$($.dialect,$.words).map(S),q=$.displayText,U=gJ(W,X.shellGitContextState);if($.dialect==="powershell"){let G=T(W5($,K,__(J,X.effectiveCwd)),J.policy);if(J.trace?.recordSegment({type:"rule-check",ruleModule:"analyze/powershell/remove-item.ts",ruleFunction:"analyzePowerShellCommandViewMatch",matched:!!G,reason:G?.reason}),G)return j_(q,G)}if(W.length===1&&W[0]?.includes(" ")&&!$.dynamicExecutable){let G=T(q2(W[0],J.scanWork),J.policy),_=G!==null&&!J.strict&&y7($,J.rootProgram,J.scanWork);if(G&&!_)return J.trace?.recordSegment({type:"dangerous-text",token:W[0],matched:!0,reason:G.reason}),{reason:G.reason,segment:q,ruleId:G.id,intent:G.intent};return J.trace?.recordSegment({type:"dangerous-text",token:W[0],matched:!1}),pJ($,B,X,U,Y,J)}let H=R2($.words,Z,{...J,commandView:$,cwd:Q,effectiveCwd:X.effectiveCwd,envAssignments:U,literalHeredocFiles:X.literalHeredocFiles,functionDefinitions:X.functionDefinitions,hasPipelineInput:K,literalShellInput:Y,analyzeNested:(G,_)=>{let O=_&&Object.hasOwn(_,"effectiveCwd")?_.effectiveCwd:X.effectiveCwd,M=w9(G,Z+1,{...J,derivedCommandWorkBudget:J.derivedCommandWorkBudget,effectiveCwd:O,envAssignments:_?.envAssignments??U,literalHeredocFiles:X.literalHeredocFiles,functionDefinitions:_?.functionDefinitions,worktreeMode:_?.worktreeMode??J.worktreeMode,trace:J.trace?rJ(J.trace,J.trace.currentSegmentIndex,!0):void 0});return M?{reason:M.reason,ruleId:M.ruleId,intent:M.intent}:null}});if(H)return{...H,segment:q};let j=pJ($,B,X,U,Y,J);if(j)return j;return hJ(W,X.shellGitContextState),null}function pJ($,Z,J,Q,X,K){let Y=Y_($,Z,J,Q??new Map,K);if(Y)return Y;return nJ($,J,"after-consumer",K.environment.paths),J.literalHeredocFiles.clear(),Z_($,Z,J,K.environment.paths),q_($,J,X,K.environment,K.trace),null}var ej=new Set([">>","<>"]);function nJ($,Z,J,Q){for(let K of $.redirections){if(!(J==="before-consumer"?$_(K):ej.has(K.operator)))continue;cJ(K.target,Z,Q)}if(J!=="before-consumer"||!R1($.words[0],"tee"))return;let X=aJ($.words.slice(1));if(!X)return;for(let K of X.operands)cJ(K,Z,Q)}function $_($){if($.operator===">"||$.operator===">|")return!0;return $.operator===">&"&&$.fd===void 0&&$.target?.provenance==="literal"&&!/^(?:[0-9]+|-)$/.test($.target.text)}function cJ($,Z,J){let Q=$?.provenance==="literal"?U2($.text,Z.effectiveCwd,J):void 0;if(!Q)return;Z.literalHeredocFiles.delete(Q)}function Z_($,Z,J,Q){if(Z)return;let X=$.redirections.find((K)=>K.operator==="<<"||K.operator==="<<-")?.heredoc;if(!X?.quotedDelimiter)return;for(let K of J_($)){let Y=U2(K.text,J.effectiveCwd,Q);if(!Y||!x7(Y))continue;if(!J.literalHeredocFiles.has(Y)&&J.literalHeredocFiles.size>=k7)throw new P1;J.literalHeredocFiles.set(Y,X.body)}}function J_($){let Z=X_($.redirections)?.target,J=dJ(Z)?[Z]:[];if(R1($.words[0],"cat"))return Q_($.words)?J:[];if(!R1($.words[0],"tee"))return[];let Q=aJ($.words.slice(1));if(!Q||Q.append||Q.hasUnsupportedOptions||!Q.operands.every(dJ))return[];return[...Q.operands,...J]}function Q_($){let Z=!1;for(let J of $.slice(1)){if(Z||J.provenance!=="literal")return!1;if(J.text==="--"){Z=!0;continue}if(!/^-u+$/.test(J.text))return!1}return!0}function X_($){let Z=$.findLast((J)=>(J.fd??([">",">|",">>",">&"].includes(J.operator)?1:0))===1);return Z?.operator===">"||Z?.operator===">|"?Z:void 0}function aJ($){let Z=[],J=!0,Q=!1,X=!1;for(let K of $){if(K.provenance!=="literal")return;if(J&&R1(K,"--")){J=!1;continue}if(J&&!K.quoted&&K.raw===K.text&&/^-[^-]/.test(K.text)){Q||=K.text.slice(1).includes("a"),X||=[...K.text.slice(1)].some((Y)=>Y!=="a"&&Y!=="i");continue}if(J&&!K.quoted&&K.raw===K.text&&K.text.startsWith("--")){Q||=K.text==="--append",X||=K.text!=="--append"&&K.text!=="--ignore-interrupts";continue}Z.push(K)}return{operands:Z,append:Q,hasUnsupportedOptions:X}}function dJ($){if(!$||$.provenance!=="literal"||$.text.length===0)return!1;if($.quoted||$.raw!==$.text)return!0;return!$.raw.startsWith("~")&&!/[{}]/.test($.raw)}function R1($,Z){return $?.text===Z&&$.raw===Z&&$.provenance==="literal"&&!$.quoted}function K_($){let Z=$.redirections.filter((Y)=>Y.operator==="<<"||Y.operator==="<<-");if(Z.length===0)return;if(Z.length!==1)return a0;let J=Z[0];if(!J?.heredoc)return a0;if(!J.heredoc.quotedDelimiter)return pj;if(J.fd!==void 0&&J.fd!==0)return a0;if($.redirections.some((Y)=>Y!==J&&["<","<<","<<-","<<<","<&","<>"].includes(Y.operator)))return a0;let Q=$.redirections.some((Y)=>Y!==J&&iJ(Y.target));if(R1($.words[0],"cat"))return Q?a0:void 0;if(R1($.words[0],"tee"))return Q||$.words.slice(1).some(iJ)?a0:void 0;let X=$.words[0],K=$.words[1];if(R1(X,"git")&&(R1(K,"apply")||R1(K,"commit")))return;if(R1(X,"gh")&&(R1(K,"pr")||R1(K,"issue"))&&R1($.words[2],"create"))return;return a0}function iJ($){return $?.parts.some((Z)=>Z.provenance==="command-substitution"&&Z.raw.startsWith(">("))??!1}function Y_($,Z,J,Q,X){if(!Z)return null;let K=$.redirections.filter((q)=>q.operator==="<<"||q.operator==="<<-"),Y=K.flatMap((q)=>q.heredoc?[q.heredoc.body]:[]);if(W_($,K,J,Q,X))return null;let B=B_($,K,X);if(B!==void 0)return B?{reason:B.reason,segment:$.displayText,ruleId:B.id,intent:B.intent}:null;let W=y9(Y.length===K.length?Y.join(`
60
- `):$.source,X);return W?{...W,segment:$.displayText}:null}function B_($,Z,J){let Q=Z.length===1?Z[0]:void 0;if(!Q?.heredoc?.quotedDelimiter||Q.fd!==void 0&&Q.fd!==0)return;let X=$.words[0];if(X?.provenance!=="literal"||!N1(X.text))return;if(!$.words.slice(1).every((q)=>q.provenance==="literal"&&q.text.startsWith("-")))return;let Y=Q.heredoc.body,B=a(J.policy,"interpreter.one-liner-paranoid",!!J.paranoidInterpreters);if(J.trace?.recordSegment({type:"interpreter",interpreter:X.text,codeArg:Y,paranoidBlocked:B}),B){let q=T(N("interpreter.one-liner-paranoid",O$),J.policy);if(q)return q}if(!L$(Y,J.scanWork))return null;let W=T(N("interpreter.dangerous-command",k0),J.policy);if(!W)return null;return J.trace?.recordSegment({type:"dangerous-text",token:Y,matched:!0,reason:W.reason}),W}function W_($,Z,J,Q,X){let K=Z.length===1?Z[0]:void 0;if(!K?.heredoc?.quotedDelimiter||K.fd!==void 0&&K.fd!==0)return!1;let Y=u0($.words,X.environment,J.effectiveCwd,Q),B=Y.words.map(S),W=x(B[0]??"");if(Y.unverifiableEnvSplit||!$1.has(W)&&!$1.has(h(W)))return!1;return C1(B)}function q_($,Z,J,Q,X){let K=TJ($,Z.effectiveCwd,Q,J);if(K===null)X?.recordSegment({type:"cwd-change",segment:$.words.map(S).join(" "),effectiveCwdNowUnknown:!0});if(K!==void 0)Z.effectiveCwd=K}function b2($){return{effectiveCwd:$.effectiveCwd,shellGitContextState:uJ($.shellGitContextState),literalHeredocFiles:new Map($.literalHeredocFiles),functionDefinitions:new Map($.functionDefinitions)}}function O3($){let Z=[];for(let J of $){if(!Z.some((Q)=>U_(Q,J)))Z.push(J);if(Z.length>cj)throw new P1}return Z}function U_($,Z){return $.effectiveCwd===Z.effectiveCwd&&I2($.literalHeredocFiles,Z.literalHeredocFiles)&&I2($.functionDefinitions,Z.functionDefinitions)&&I2($.shellGitContextState.effectiveEnvAssignments,Z.shellGitContextState.effectiveEnvAssignments)&&I2($.shellGitContextState.shellAssignments,Z.shellGitContextState.shellAssignments)&&H_($.shellGitContextState.exportedNames,Z.shellGitContextState.exportedNames)&&$.shellGitContextState.allexport===Z.shellGitContextState.allexport&&$.shellGitContextState.keywordExport===Z.shellGitContextState.keywordExport}function I2($,Z){if($===Z)return!0;if(!$||!Z||$.size!==Z.size)return!1;return[...$].every(([J,Q])=>Z.get(J)===Q&&Z.has(J))}function G_($,Z){let J=O4($);return J===void 0?void 0:Z.get(J)}function H_($,Z){return $.size===Z.size&&[...$].every((J)=>Z.has(J))}function j_($,Z){if(!Z)return null;return{reason:Z.reason,segment:$,ruleId:Z.id,intent:Z.intent}}function __($,Z=$.effectiveCwd){let J=Z===null;return{environment:$.environment,cwd:J?void 0:Z??$.cwd,originalCwd:J?void 0:$.cwd,strict:$.strict,paranoid:$.paranoidRm,allowTmpdirVar:$.allowTmpdirVar,protectedGitMetadata:$.protectedGitMetadata,policy:$.policy}}function y9($,Z){let J=T(q2($,Z.scanWork),Z.policy),Q=Z.trace?.currentSegmentIndex??Z.trace?.allocateSegment(),X={type:"dangerous-text",token:$,matched:!!J,reason:J?.reason};if(Z.trace?.recordSegment(X,Q),!J&&/^(?:cd|pushd)\s/.test($))Z.trace?.recordSegment({type:"cwd-change",segment:$,effectiveCwdNowUnknown:!0},Q);return J?{reason:J.reason,segment:$,ruleId:J.id,intent:J.intent}:null}function sJ($,Z){let J={type:"strict-unparseable",rawCommand:$,reason:V0};if(Z.trace?.currentSegmentIndex===void 0)Z.trace?.recordGlobal(J);else Z.trace.recordSegment(J)}function Cz($,Z){return v9($,Z)}function v9($,Z,J,Q){let X=w9($,0,{...Z,...T7(Z),factStore:Q},J);if(!X)return null;return{kind:"deny",reason:X.reason,intent:X.intent??"manual_only",...X.ruleId?{ruleId:X.ruleId}:{},evidence:[{kind:"command",command:$,segment:X.segment}]}}function oJ($,Z,J,Q,X){if(J.kind!=="command")return{toolName:$,input:Z,route:J,context:Q};return{toolName:$,input:Z,route:J,context:Q,command:X}}var u9=[{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"}],N3={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},O_=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],L_=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],h9=[{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"]},...L_.flatMap(($)=>O_.map((Z)=>({id:["secret.home",$.idSlug,Z.slice(1)].join("."),category:"Home path",label:[$.label,Z].join(""),description:["Blocks home ",$.label,Z," credential backup files."].join(""),suffixParts:[...$.directoryParts,[$.basename,Z].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 V3=[{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","/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"]}],tJ=[{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"}],M_=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],g9=tJ.map(($)=>({id:`secret.variant.${$.slug}.separator`,category:"Variant",label:`${$.label}-* / ${$.label}_*`,description:`Blocks ${$.label} variants with dash or underscore suffixes.`,prefix:$.prefix})),k9=tJ.flatMap(($)=>M_.map((Z)=>({id:`secret.variant.${$.slug}.${Z.slice(1)}`,category:"Variant",label:`${$.label}${Z}`,description:`Blocks ${$.label}${Z} private credential variants.`,prefix:$.prefix,suffix:Z}))),f2={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)$/},x9=["agilekeychain","asc","bek","cscfg","fve","gnucash","jks","keychain","kwallet","mdf","ovpn","p12","pcap","pem","pfx","pkcs12","psafe3","rdp","sdf","tblk","tpm"].map(($)=>({id:`secret.ext.${$}`,category:"Extension",label:`.${$}`,description:`Blocks files with the .${$} extension.`,extension:$})),l9=[{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?$/}],eJ=[...u9,N3,...h9,...g9,...k9,f2,...x9,...l9,...V3].map(($)=>({id:$.id,category:$.category,label:$.label,...$.category==="Coding CLI config"?{defaultOff:!0}:{},..."paths"in $?{paths:$.paths}:{description:$.description}})),$Q=new Set(V3.flatMap(($)=>$.category==="Coding CLI config"?[$.id]:[])),F_=eJ.map(($)=>$.id),R3=new Set(F_);import{createRequire as N_}from"node:module";var ZQ=Object.freeze(["hard_stop","use_alternative","scope_down","manual_only","stop_and_explain"]);var P2=64,QQ="Rule config exceeds CC Safety Net's safe source limit.";var JQ=Object.freeze({maxSources:64,concurrency:4,maxRequests:131,maxResponseBytes:67108864});function D3($={}){return{requests:0,responseBytes:0,maxRequests:$.maxRequests??JQ.maxRequests,maxResponseBytes:$.maxResponseBytes??JQ.maxResponseBytes}}function z3($){return{controller:new AbortController,budget:D3(),resolveUrl:$}}function XQ($){if($.requests>=$.maxRequests)throw Error("Rule synchronization exceeds CC Safety Net's safe resource limits.");$.requests++}function KQ($,Z){if(Z>$.maxResponseBytes-$.responseBytes)throw $.responseBytes+=Z,Error("Rule synchronization exceeds CC Safety Net's safe resource limits.");$.responseBytes+=Z}var V_=N_(import.meta.url),YQ,R_=Array(P2+1).fill("over-limit"),BQ=/^[^/]+\/[^/]+$/,D_=/^sha256:[a-f0-9]{64}$/,b3=`must be an integer between ${p3} and ${c3}`,z_=["version","rules","overrides","transparent_wrappers"],b_=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function WQ($){if(!E1($)||!Array.isArray($.rules)||$.rules.length<=P2)return $;return{$schema:$.$schema,version:$.version,rules:R_,overrides:$.overrides,transparent_wrappers:$.transparent_wrappers}}function I_(){let $=V_("zod"),Z=(F)=>{let R=$.superRefine(F);return R._zod.def.when=()=>!0,R},J=$.enum(ZQ),Q=$.union([$.literal("off"),$.looseObject({reason:$.string({error:"required non-empty string"}).min(1,"required non-empty string").max(Y$,`must be at most ${Y$} characters`).describe("Replacement block reason"),intent:J.optional()})],{error:'must be "off" or an object'}).describe("Disable a rule or replace its block reason and intent."),X=$.string({error:"must be a rulebook source string"}).min(1,"must be a non-empty rulebook source string"),K=$.string({error:"must be a command string"}).regex(T0,"must match command pattern").describe("Command name such as 'git', 'docker', or 'rtk'."),Y=$.looseObject({$schema:$.unknown().optional().describe("JSON Schema reference for IDE support"),version:$.literal(1).describe("Schema version (must be 1)"),rules:$.array(X,{error:"must be an array of rulebook source strings"}).max(P2,QQ).default([]).describe("Rulebook source strings such as project-rules or owner/repo#main/team-rules"),overrides:$.record($.string().meta({pattern:BQ.source}),Q).default({}).describe("Rule overrides by id"),transparent_wrappers:$.array(K,{error:"must be an array of command strings"}).default([]).describe("Commands that transparently execute a visible protected child command")}),B=(F,R)=>{if(!E1(F))return;if(Array.isArray(F.rules)&&F.rules.length<=P2){let I=new Set;F.rules.forEach((C,y)=>{if(typeof C!=="string"||C==="")return;if(C.trim()===""){R.addIssue({code:"custom",message:"must be a non-empty rulebook source string",path:["rules",y]});return}let w=m$(C);if(w){R.addIssue({code:"custom",message:w,path:["rules",y]});return}if(I.has(C)){R.addIssue({code:"custom",message:`duplicate rulebook source "${C}"`,path:["rules",y]});return}I.add(C)})}if(E1(F.overrides))for(let I of Object.keys(F.overrides)){if(BQ.test(I))continue;R.addIssue({code:"custom",message:"must use <rulebook-name>/<rule-name>",path:["overrides",I]})}if(!Array.isArray(F.transparent_wrappers))return;let b=new Set;F.transparent_wrappers.forEach((I,C)=>{if(typeof I!=="string"||!T0.test(I))return;if(b.has(I)){R.addIssue({code:"custom",message:`duplicate command "${I}"`,path:["transparent_wrappers",C]});return}if(E7(I)){R.addIssue({code:"custom",message:`reserved command "${I}" cannot be a wrapper`,path:["transparent_wrappers",C]});return}b.add(I)})},W=$.preprocess(WQ,Y.check($.superRefine(B))),q=$.preprocess(WQ,Y.check(Z(B))),U=$.strictObject({fail_closed:$.boolean().optional(),paranoid_rm:$.boolean().optional(),paranoid_interpreters:$.boolean().optional()}),H=(F,R)=>$.intersection($.record($.string().refine((b)=>F.has(b),{error:(b)=>`unknown ${R} rule id "${String(b.input)}"`}),$.unknown()),$.record($.string(),$.enum(["on","off"]))),j=(F)=>$.array($.string({error:"must be a non-empty path string"}),{error:"must be an array of paths"}).check(Z((R,b)=>{if(!Array.isArray(R))return;let I=X$();R.forEach((C,y)=>{if(typeof C!=="string")return;let w=F(C,I);if(w)b.addIssue({code:"custom",message:w,path:[y]})})})),G=$.strictObject({version:$.literal(1),safety:$.strictObject({level:$.enum(["standard","strict","paranoid"]).optional(),overrides:U.optional()}).optional(),workflow:$.strictObject({worktree_mode:$.boolean().optional()}).optional(),destructive_command_protection:$.strictObject({enabled:$.boolean().optional(),overrides:H(s2,"destructive command").optional(),allow_paths:j(n4).optional()}).optional(),secret_protection:$.strictObject({enabled:$.boolean().optional(),overrides:H(R3,"secret protection").optional(),deny_paths:j(a4).optional()}).optional(),audit:$.strictObject({retention_days:$.number({error:b3}).int(b3).min(p3,b3).max(c3,b3).optional().describe("Days of audit log history to keep before the sweep deletes it")}).optional()}),_=(F)=>{let R=(y,w)=>F==="legacy"?y:w,b=R("must match pattern (letters, numbers, hyphens, underscores)","must match command pattern"),I=`required non-empty string up to ${Y$} characters`,C=$.looseObject({name:$.string({error:"required string"}).regex(z1,R("must match pattern (letters, numbers, hyphens, underscores; max 64 chars)","must match rule name pattern")),command:$.string({error:R("required string","required string matching command pattern")}).regex(T0,R(b,"required string matching command pattern")),subcommand:$.string({error:R("must be a string if provided","must match command pattern")}).regex(T0,b).optional(),block_args:$.array($.string({error:R("must be a string","must be a non-empty string")}).refine((y)=>y!=="",{error:R("must not be empty","must be a non-empty string")}),{error:R("required array","required non-empty array")}).refine((y)=>y.length>0,{error:R("must have at least one element","required non-empty array")}),reason:$.string({error:R("required string",I)}).refine((y)=>y!=="",{error:R("must not be empty",I)}).refine((y)=>y.length<=Y$,{error:R(`must be at most ${Y$} characters`,I)}),intent:J.optional()},{error:"must be an object"});return $.array(C,{error:R("must be an array","required array")}).check(Z((y,w)=>{if(!Array.isArray(y))return;let k=new Set;y.forEach((B1,P)=>{let v=E1(B1)?B1.name:void 0;if(typeof v!=="string")return;if(k.has(v.toLowerCase())){w.addIssue({code:"custom",message:`duplicate rule name "${v}"`,path:[P,"name"]});return}k.add(v.toLowerCase())})}))},O=$.looseObject({version:$.literal(1),rules:_("legacy").optional()}),M="required string matching rule name pattern",L=$.looseObject({command:$.string({error:"required non-empty string"}).refine((F)=>F.trim()!=="",{error:"required non-empty string"}),expect:$.enum(["blocked","allowed"]),rule:$.string({error:"must be a string if provided"}).optional()},{error:"must be an object"}).check(Z((F,R)=>{if(!E1(F))return;if(F.expect!=="blocked"||typeof F.rule==="string")return;R.addIssue({code:"custom",message:"required string for blocked fixtures",path:["rule"]})})),D=$.looseObject({name:$.string({error:"required string matching rule name pattern"}).regex(z1,"required string matching rule name pattern"),version:$.string({error:"required non-empty string"}).refine((F)=>F!=="",{error:"required non-empty string"}),allowed_commands:$.array($.string({error:"must match command pattern"}).regex(T0,"must match command pattern"),{error:"required array"}).check(Z((F,R)=>{if(!Array.isArray(F))return;let b=new Set;F.forEach((I,C)=>{if(typeof I!=="string"||!T0.test(I))return;if(b.has(I)){R.addIssue({code:"custom",message:`duplicate command "${I}"`,path:[C]});return}b.add(I)})})),rules:_("rulebook"),tests:$.array(L,{error:"must be an array if provided"}).optional()}).check(Z((F,R)=>{if(!E1(F))return;let b=new Set(m9(F));if(Array.isArray(F.tests)){let C=new Set(F.tests.flatMap((y)=>E1(y)&&y.expect==="blocked"&&typeof y.rule==="string"?[y.rule]:[]));for(let y of C){if(b.has(y))continue;R.addIssue({code:"custom",message:`blocked fixture references unknown rule "${y}"`,path:["tests"]})}}if(!Array.isArray(F.allowed_commands)||!Array.isArray(F.rules))return;let I=new Set(F.allowed_commands.filter((C)=>typeof C==="string"));F.rules.forEach((C,y)=>{let w=E1(C)?C.command:void 0;if(typeof w!=="string"||I.has(w))return;R.addIssue({code:"custom",message:`"${w}" must be listed in allowed_commands`,path:["rules",y,"command"]})})})),z=$.string({error:"required string"}).refine((F)=>F.trim()!=="",{error:"required string"}),f=$.looseObject({spec:z,name:z,version:z,digest:$.string({error:"required sha256 digest"}).regex(D_,"required sha256 digest")},{error:"must be an object"}),A=$.looseObject({rulebooks:$.array($.intersection(f,$.discriminatedUnion("kind",[$.object({kind:$.literal("local-directory"),path:z}),$.object({kind:$.literal("github"),owner:z,repo:z,ref:z,commit:z,path:z,display_ref:$.unknown().optional()})],{error:(F)=>{if(!E1(F.input))return"must be an object";let R=F.input.kind;return typeof R==="string"?`unknown kind "${R}"`:"required string"}})))});return{RulesConfigSchema:W,RulesConfigDiagnosticSchema:q,RuleOverrideSchema:Q,UserPolicySchema:G,LegacyConfigSchema:O,RulebookSchema:D,RulesLockfileSchema:A}}function f$(){return YQ??=I_(),YQ}function qQ(){return f$().RulesConfigSchema}function f_(){return f$().UserPolicySchema}function dz(){return f$().LegacyConfigSchema}function UQ(){return f$().RulebookSchema}function GQ(){return f$().RulesLockfileSchema}function m9($){let Z=E1($)?$.rules:void 0;return(Array.isArray(Z)?Z:[]).flatMap((J)=>{let Q=E1(J)?J.name:void 0;return typeof Q==="string"?[Q]:[]})}function HQ($){let Z=f$().RulesConfigDiagnosticSchema.safeParse($);if(Z.success)return{errors:[],sources:new Set(Z.data.rules)};return{errors:P$(_Q(Z.error.issues,z_)),sources:E_($,Z.error.issues)}}function C2($){let Z=f_().safeParse($);if(Z.success)return[];return P$(_Q(Z.error.issues,b_)," ")}function P$($,Z=": ",J=" "){return[...new Set($.flatMap((Q)=>jQ(Q,Z,J,[])))]}function jQ($,Z,J,Q){let X=[...Q,...$.path],K=A_(X);if($.code==="unrecognized_keys")return $.keys.map((Y)=>`${K?`${K}.`:""}unknown field "${Y}"`);if($.code==="invalid_key")return $.issues.map((Y)=>Y.message);if($.code==="invalid_union"){let Y=$.errors.flat().filter((B)=>B.path.length>0);if(Y.length>0)return Y.flatMap((B)=>jQ(B,Z,J,X))}if(X.length===0)return[$.code==="invalid_type"?"Config must be an object":$.message];if(X.length===1&&($.code==="too_big"||$.code==="too_small")&&$.origin==="array")return[$.message];return[`${K}${X.length===1?J:Z}${P_($)}`]}function P_($){if($.code==="invalid_value")return`must be ${C_($.values)}`;if($.code!=="invalid_type"||!$.message.startsWith("Invalid input:"))return $.message;if($.expected==="object"||$.expected==="record")return"must be an object if provided";return $.expected==="boolean"?"must be a boolean":$.message}function C_($){if($.length>3)return`one of ${$.join(", ")}`;let Z=$.map((J)=>typeof J==="string"?`"${J}"`:String(J));if(Z.length<2)return`${Z[0]}`;return`${Z.slice(0,-1).join(", ")}${Z.length>2?",":""} or ${Z.at(-1)}`}function A_($){return $.map((Z,J)=>{if(typeof Z==="number")return`[${Z}]`;return J===0?String(Z):`.${String(Z)}`}).join("")}function _Q($,Z){let J=$.map((K)=>K.path[1]),Q=[...new Set(J.filter((K)=>typeof K==="string"))],X=(K,Y)=>[K.path.length===0?-1:Z.indexOf(String(K.path[0])),typeof Y==="number"?Y:Q.indexOf(String(Y)),K.code==="custom"?0:1];return $.map((K,Y)=>({issue:K,rank:X(K,J[Y])})).sort((K,Y)=>K.rank[0]-Y.rank[0]||K.rank[1]-Y.rank[1]||K.rank[2]-Y.rank[2]).map((K)=>K.issue)}function E_($,Z){let J=E1($)?$.rules:void 0;if(!Array.isArray(J))return new Set;if(Z.some((X)=>X.path.length===1&&X.path[0]==="rules"))return new Set;let Q=new Set(Z.filter((X)=>X.path[0]==="rules"&&typeof X.path[1]==="number").map((X)=>X.path[1]));return new Set(J.filter((X,K)=>typeof X==="string"&&!Q.has(K)))}function E1($){return!!$&&typeof $==="object"&&!Array.isArray($)}var OQ={version:1,rules:[],overrides:{},transparent_wrappers:[]};function T_($){return HQ($)}function C$($){try{let Z=X0(LQ($));if(Z===null)return{config:null,errors:[]};if(!Z.trim())return{config:null,errors:["Config file is empty"]};let J=JSON.parse(Z),Q=T_(J);if(Q.errors.length>0)return{config:null,errors:Q.errors};let X=qQ().parse(J);return{config:{version:1,rules:X.rules??[],overrides:X.overrides??{},transparent_wrappers:X.transparent_wrappers??[]},errors:[]}}catch(Z){if(Z instanceof u)return{config:null,errors:[Z.message]};return{config:null,errors:["Invalid JSON"]}}}function oz($){let Z=C$($);if(Z.errors.length>0)return{ok:!1,result:{ok:!1,errors:Z.errors,warnings:[],entries:[]}};return{ok:!0,config:Z.config??OQ}}function tz($,Z=[]){I3($,{version:1,rules:Z,overrides:{},transparent_wrappers:[]})}function ez($,Z="project-rules"){I3($,{rulebook_version:1,name:Z,version:"1.0.0",description:Z==="project-rules"?"Project-specific CC Safety Net rules.":"User-specific CC Safety Net rules.",author:Z==="project-rules"?"project":"user",allowed_commands:["docker"],rules:[{name:"block-docker-system-prune",command:"docker",subcommand:"system",block_args:["prune"],reason:"Use targeted cleanup instead."}],tests:[{command:"docker system prune",expect:"blocked",rule:"block-docker-system-prune"}]})}function I3($,Z,J,Q){GZ(LQ($),`${JSON.stringify(Z,null,2)}
61
- `,J,Q)}function LQ($){return typeof $==="string"?u2($):$}import{chmodSync as S_,existsSync as p9,mkdirSync as y_,readFileSync as c9}from"node:fs";import{dirname as NQ,join as w_}from"node:path";var v_=new Set(["standard","strict","paranoid"]),P3={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:[]},audit:{retention_days:p2}};function T$($){return w_(NQ(K0($)),x2)}function Hb($={}){let Z=T$($);if(!p9(Z))return{path:Z,exists:!1,raw:"",policy:A$(),errors:[]};let J=c9(Z,"utf-8");if(!J.trim())return{path:Z,exists:!0,raw:J,policy:A$(),errors:["Config file is empty"]};try{let Q=JSON.parse(J),X=C2(Q);return{path:Z,exists:!0,raw:J,policy:X.length>0?A$():E$(Q),errors:X}}catch(Q){return{path:Z,exists:!0,raw:J,policy:A$(),errors:[`Invalid JSON: ${Q instanceof Error?Q.message:String(Q)}`]}}}function f3($,Z={}){let J=T$(Z),Q=C2($),X=Q.length>0?A$():E$($);if(Q.length>0)return{path:J,policy:X,errors:Q};return y_(NQ(J),{recursive:!0,mode:448}),I3(J,X,384),S_(J,384),{path:J,policy:X,errors:[]}}function jb($){let Z=C2($);if(Z.length>0)return{errors:Z};return{preview:u_(E$($)),errors:[]}}function u_($){let Z=c4({safety:DQ($.safety)}),J=n3({destructiveCommandProtectionEnabled:$.destructive_command_protection.enabled,destructiveCommandRuleOverrides:$.destructive_command_protection.overrides},Z.capabilities),Q=Object.values(J),X=Q.filter((Y)=>Y.source!=="catastrophic"),K=Object.values($.destructive_command_protection.overrides);return{selectedPreset:$.safety.level,effectiveLevel:Z.effectiveLevel,capabilities:Z.capabilities,rules:J,counts:{enabled:X.filter((Y)=>Y.enabled).length,disabled:X.filter((Y)=>!Y.enabled).length,explicitOn:K.filter((Y)=>Y==="on").length,explicitOff:K.filter((Y)=>Y==="off").length,effectiveCustomizations:Q.filter((Y)=>Y.changesInherited).length,inheritedRequiresStrict:Q.filter((Y)=>!Y.enabled&&!Y.override&&Y.activationCapability==="fail_closed").length,inheritedRequiresParanoid:Q.filter((Y)=>!Y.enabled&&!Y.override&&(Y.activationCapability==="paranoid_rm"||Y.activationCapability==="paranoid_interpreters")).length}}}function _b($={}){let Z=T$($);if(!p9(Z))return f3(P3,$);let J=c9(Z,"utf-8");if(!J.trim())return f3(P3,$);try{return f3(E$(JSON.parse(J)),$)}catch{return f3(P3,$)}}function VQ($={}){let Z=k_(T$($));return{safety:Z.policy.safety,worktreeMode:Z.policy.worktreeMode,destructiveCommandProtectionEnabled:Z.policy.destructiveCommandProtectionEnabled,destructiveCommandRuleOverrides:{...Z.policy.destructiveCommandRuleOverrides},destructiveCommandAllowPaths:[...Z.policy.destructiveCommandAllowPaths],secretProtection:Z.policy.secretProtection,errors:Z.errors,...Z.fallback?{fallback:Z.fallback}:{}}}function E$($){if(!J0($))return A$();let Z=J0($.safety)?$.safety:{},J=J0(Z.overrides)?Z.overrides:{},Q=J0($.workflow)?$.workflow:{},X=J0($.destructive_command_protection)?$.destructive_command_protection:{},K=J0($.secret_protection)?$.secret_protection:{};return{version:1,safety:{level:v_.has(Z.level)?Z.level:"standard",overrides:{...typeof J.fail_closed==="boolean"?{fail_closed:J.fail_closed}:{},...typeof J.paranoid_rm==="boolean"?{paranoid_rm:J.paranoid_rm}:{},...typeof J.paranoid_interpreters==="boolean"?{paranoid_interpreters:J.paranoid_interpreters}:{}}},workflow:{worktree_mode:typeof Q.worktree_mode==="boolean"?Q.worktree_mode:!1},destructive_command_protection:{enabled:typeof X.enabled==="boolean"?X.enabled:!0,overrides:MQ(X.overrides,s2),allow_paths:g_(X.allow_paths)},secret_protection:{enabled:typeof K.enabled==="boolean"?K.enabled:!0,overrides:MQ(K.overrides,R3),deny_paths:h_(K.deny_paths)},audit:{retention_days:c2(J0($.audit)?$.audit.retention_days:void 0)}}}function MQ($,Z){if(!J0($))return{};return Object.fromEntries(Object.entries($).flatMap(([J,Q])=>Z.has(J)&&(Q==="on"||Q==="off")?[[J,Q]]:[]))}function h_($){if(!Array.isArray($))return[];let Z=X$();return $.filter((J)=>a4(J,Z)===null)}function g_($){if(!Array.isArray($))return[];let Z=X$();return $.filter((J)=>n4(J,Z)===null)}function J0($){return!!$&&typeof $==="object"&&!Array.isArray($)}function A$(){return structuredClone(P3)}function k_($){let Z=x_();if(!p9($)){let J=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!J0(J))return{policy:Z,errors:[]};return{policy:FQ(E$(J)),errors:[]}}try{let J=c9($,"utf-8");if(!J.trim())return{policy:Z,errors:[`${$}: Config file is empty`],fallback:"defaults"};let Q=JSON.parse(J),X=C2(Q),K=FQ(E$(Q));if(X.length>0)return{policy:K,errors:X.map((Y)=>`${$}: ${Y}`),fallback:J0(Q)?"salvaged":"defaults"};return{policy:K,errors:[]}}catch{return{policy:Z,errors:[`${$}: Invalid JSON`],fallback:"defaults"}}}function RQ($){let Z=Object.entries($),J=new Set(Z.flatMap(([Q,X])=>X==="on"?[Q]:[]));return new Set([...[...$Q].filter((Q)=>!J.has(Q)),...Z.flatMap(([Q,X])=>X==="off"?[Q]:[])])}function x_(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:RQ({}),denyPaths:[]}}}function FQ($){return{safety:DQ($.safety),worktreeMode:$.workflow.worktree_mode,destructiveCommandProtectionEnabled:$.destructive_command_protection.enabled,destructiveCommandRuleOverrides:{...$.destructive_command_protection.overrides},destructiveCommandAllowPaths:[...$.destructive_command_protection.allow_paths],secretProtection:{enabled:$.secret_protection.enabled,disabledRules:RQ($.secret_protection.overrides),denyPaths:[...$.secret_protection.deny_paths]}}}function DQ($){return{level:$.level,overrides:{failClosed:$.overrides.fail_closed,paranoidRm:$.overrides.paranoid_rm,paranoidInterpreters:$.overrides.paranoid_interpreters}}}import{dirname as d9}from"node:path";var fQ="This path contains the protected policy config and you must not modify or delete it.",l_=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function PQ($){let Z=y0(B0()),J=s_($.invocation.context.executionCwd,Z);if($.invocation.route.kind==="patch")return zQ($.paths.map((X)=>X.raw),!1,$.invocation.context.executionCwd,J,Z);let Q=_1($,"input-candidate");if($.invocation.route.kind==="command")return Q?bQ(Q.shell,$.invocation.context.executionCwd,J,Z):null;if($.invocation.route.kind==="unknown"&&Q){let X=bQ(Q.shell,$.invocation.context.executionCwd,J,Z);if(X)return X}return zQ($.paths.map((X)=>X.raw),$.invocation.route.kind==="grep"||$.invocation.route.kind==="glob"||t2($.invocation.toolName),$.invocation.context.executionCwd,J,Z)}function zQ($,Z,J,Q,X){if(Z)return null;let K=$.find((Y)=>A2(Y,J,Q,X));return K?{target:K}:null}function bQ($,Z,J,Q){let X=P4($,Z,Q,{findSegmentTarget:(K,Y)=>m_(K,Y,J,Q)?.target??null,isRedirectionTarget:(K,Y)=>A2(K,Y.cwd,J,Q),findMalformedTarget:(K)=>i_(K,Z,J,Q)?.target??null,normalizeCwd:K1});return X?{target:X}:null}function m_($,Z,J,Q){if(Z2($))return null;let X=Q.environment,K=I1([...$],X),Y=h(K[0]??"").toLowerCase(),B=K.slice(1);if(Y==="rm"&&p_(B)){let W=c_(B).find((q)=>IQ(L1(q,Z.variables),Z.cwd,J,Q));if(W)return{target:W}}if(Y==="find"){if($3(K,1)||Z9(K,X)){let q=(e4(g(K))??g(["."])).find((U)=>{let H=L1(U.text,Z.variables);return A2(H,Z.cwd,J,Q)||IQ(H,Z.cwd,J,Q)})?.text;if(q)return{target:q}}}if(Y==="mv"){let W=C4(B).sources.find((q)=>r_(L1(q,Z.variables),Z.cwd,J,Q));if(W)return{target:W}}if(d_($,X))return null;for(let W of $)for(let q of CQ(W))if(A2(L1(q,Z.variables),Z.cwd,J,Q))return{target:q};return null}function p_($){return $.some((Z)=>Z==="--recursive"||Z.startsWith("-")&&!Z.startsWith("--")&&/[rR]/.test(Z.slice(1)))}function c_($){let Z=$.indexOf("--");if(Z!==-1)return[...$.slice(0,Z).filter((J)=>!J.startsWith("-")),...$.slice(Z+1)];return $.filter((J)=>!J.startsWith("-"))}function d_($,Z){let J=I1([...$],Z);if(J.length===0)return!1;let Q=h(J[0]??"").toLowerCase();if(!l_.has(Q))return!1;if(Q!=="sed")return!0;return!J.slice(1).some((X)=>X.startsWith("-i")||X==="--in-place"||X.startsWith("--in-place="))}function i_($,Z,J,Q){for(let X of $.split(/\s+/))for(let K of CQ(X))if(A2(K,Z,J,Q))return{target:K};return null}function CQ($){let Z=$.trim().replace(/^['"]|['"]$/g,""),J=Z.indexOf("=");return J===-1||J===Z.length-1?[Z]:[Z,Z.slice(J+1)]}function s_($,Z){let J=K1(T$(),$,Z),Q=d9(J),X=new Set;for(let K=Q;;K=d9(K))if(X.add(S$(K)),d9(K)===K)break;return{file:S$(J),directory:S$(Q),directoryAndAncestors:X}}function A2($,Z,J,Q){return S$(K1($,Z,Q))===J.file}function IQ($,Z,J,Q){return J.directoryAndAncestors.has(S$(K1($,Z,Q)))}function r_($,Z,J,Q){let X=S$(K1($,Z,Q));return X===J.file||J.directoryAndAncestors.has(X)}function S$($){return process.platform==="win32"?$.toLowerCase():$}import{homedir as n_}from"node:os";import{isAbsolute as s9,resolve as hQ}from"node:path";import{fileURLToPath as a_}from"node:url";var gQ="Access to a sensitive path is not allowed.",kQ=new Set(["echo","printf"]),o_=new Set(["find"]),t_=new Set(["-exec","-execdir"]),e_=new Set([";","+"]),$O=new Set(["-delete","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),ZO=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),JO=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),QO=new Set(["node","bun"]),XO=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),KO=new Set(["append","awk","base64","cat","chmod","chown","connect","copy","cp","database","dd","eval","exec","fetch","file","function","grep","head","include","load","move","mv","open","popen","read","remove","rename","require","rg","rm","sed","shell","source","spawn","strings","system","tail","tar","truncate","unlink","write","xxd","zip"]),xQ=new Set(["-c","-e","-r","-E","--eval","--exec"]),YO=new Set(["src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js"]),BO=new Map([["c",new Set(["bash","sh","zsh","dash","ksh","python"])],["e",new Set(["node","deno","bun","ruby","perl","rscript","osascript"])],["E",new Set(["perl"])],["r",new Set(["php"])]]),WO=new Set(["grep","rg"]),AQ="f",EQ="file",qO="files",UO=new Set(["e","f"]),GO=new Set(["regexp","file"]),HO=new Set(["e","f","A","B","C","m"]),jO=new Set(["regexp","file","after-context","before-context","context","max-count"]),_O=new Set(["|","|&"]),i9="__CC_SAFETY_NET_PIPE_INPUT__",lQ=new Set(["bash","sh","zsh","dash","ksh"]),OO=new Map([["bash",new Set(["-O"])],["sh",new Set(["-O"])],["zsh",new Set(["-o"])],["dash",new Set(["-o"])],["ksh",new Set(["-o"])],["python",new Set(["-W","-X"])],["node",new Set(["-r","--require","--loader","--import","--input-type"])]]);function TQ($,Z,J,Q,X){let K=d$();for(let Y of $){if(eO(Y,Z,J?.denyPaths??[],Q,K))return{target:Y,ruleId:"secret.deny-path"};if(X&&!X.has(Y))continue;let B=oO(Y,Z,J,K);if(B)return{target:Y,ruleId:B}}return null}function mQ($,Z,J={}){let Q=SQ($),X=TQ(Q,$.invocation.context.executionCwd,Z,$.invocation.context.configCwd),K=X?.ruleId!=="secret.deny-path"&&J.strict===!1?SQ($,{refineJavaScriptInlineData:!0}):Q,Y=K.length===Q.length?X:TQ(Q,$.invocation.context.executionCwd,Z,$.invocation.context.configCwd,new Set(K));if(Y?.ruleId!=="secret.deny-path"&&J.strict===!1&&LO($))return null;return Y}function LO($){if($.invocation.route.kind!=="command")return!1;let Z=_1($,"input-candidate")??_1($,"declared-command");if(!Z)return!1;if(Z.program.nodes.some((Y)=>Y.kind==="command"&&Y.nested.length>0))return!1;let J=[];for(let Y of Z.shell.entries){if(Y.kind==="operator"&&Y.boundary)return!1;if(Y.kind==="redirection")return!1;if(Y.kind!=="operator")J.push(d1(Y.text))}let Q=w$(J);if(Q.length===0)return!1;let X=o0(Q[0]??"").toLowerCase(),K=Q.slice(1);if(X==="test")return K.length===2&&(K[0]==="-e"||K[0]==="-f");if(X!=="find")return!1;return!K.some((Y)=>$O.has(Y))}function SQ($,Z={}){if($.invocation.route.kind==="command"){let Q=_1($,"input-candidate");return Q?S2(Q.shell,$.store,Z):[]}if($.invocation.route.kind!=="unknown")return $.paths.map((Q)=>Q.raw);let J=_1($,"input-candidate");return[...J?S2(J.shell,$.store,Z):[],...$.paths.map((Q)=>Q.raw)]}function S2($,Z,J){if($.status==="structural-limit")throw new z0;if($.status==="unclosed-quote")return[];if($.status==="invalid")throw Error("Unable to parse command for secret protection");let Q=[...$.assignmentFallbacks,...uO(d1($.source),Z,J)],X=[],K=null;for(let Y of $.entries){if(Y.kind==="operator"){if(!Y.boundary)continue;if(X.length>0){if(Q.push(...C3(X,Z,J)),K!==null)Q.push(...yQ(K,X,Z,J));K=_O.has(Y.operator)?X:null,X=[]}else K=null;continue}if(Y.kind==="redirection"){let B=Y.target?d1(Y.target):void 0;if(B&&Y.targetOrder==="legacy-segment")X.push(B);else if(B)Q.push(B);continue}X.push(d1(Y.text))}if(X.length>0){if(Q.push(...C3(X,Z,J)),K!==null)Q.push(...yQ(K,X,Z,J))}return Q}function C3($,Z,J){let Q=fO($),X=w$($);if(X.length===0)return Q;let K=X[0]??"",Y=o0(K).toLowerCase(),B=X.slice(1),W=MO(K,Y,B);if(W)return[...Q,...W];if(kQ.has(Y))return Q;if(WO.has(Y))return[...Q,...cO(B)];if(o_.has(Y))return[...Q,...PO(B,Z,J)];if(F1.has(Y))return[...Q,...B.flatMap((q)=>wQ("awk",q)),...B.flatMap((q)=>AO(q,Z,J)),...B.flatMap(EO)];if(dQ(Y)){if(lQ.has(Y)){let q=Y7(Y,B);if(q!==null&&Z.getShellSyntax(q).status==="structural-limit")throw new z0}return[...Q,...CO(Y,B,J)]}return[...Q,...B.flatMap((q)=>wQ(Y,q))]}function MO($,Z,J){let Q=Z==="cc-safety-net"&&J[0]==="explain",X=(Z==="bun"||Z==="node")&&FO(J[0])&&J[1]==="explain";if(!Q&&!X)return null;let K=X?[$,J[0]??""]:[$],Y=J.slice(X?2:1);for(let B=0;B<Y.length;B++){let W=Y[B];if(W==="--json"||W==="--help"||W==="-h")continue;if(W==="--cwd"){let q=Y[B+1];if(q&&!q.startsWith("--"))K.push(q);B++;continue}return K}return K}function FO($){let Z=$?.replaceAll("\\","/");return[...YO].some((J)=>Z===J||Z?.endsWith(`/${J}`))}function yQ($,Z,J,Q){if(zO(Z,J,Q))return NO($);let X=bO(Z);if(X===null)return[];return VO($).flatMap((K)=>lQ.has(X)?S2(J.getShellSyntax(K),J,Q):sQ(K))}function NO($){let Z=w$($);if(Z.length===0)return[];let J=o0(Z[0]??"").toLowerCase();if(!kQ.has(J))return[];return Z.slice(1)}function VO($){let Z=w$($);if(Z.length===0)return[];let J=o0(Z[0]??"").toLowerCase(),Q=Z.slice(1);if(J==="echo"){let X=Q.findIndex((K)=>!/^-[neE]+$/.test(K));return[(X===-1?[]:Q.slice(X)).join(" ")]}if(J==="printf")return RO(Q);return[]}function RO($){let Z=$[0];if(Z===void 0)return[];let J=(Z.match(/%%|%[bqs]/g)??[]).filter((X)=>X!=="%%").length;if(J===0||$.length===1)return[pQ(Z)];let Q=$.slice(1);return Array.from({length:Math.ceil(Q.length/J)},(X,K)=>DO(Z,Q.slice(K*J,(K+1)*J)))}function DO($,Z){let J=0;return pQ($.replace(/%%|%[bqs]/g,(Q)=>{if(Q==="%%")return"%";let X=Z[J]??"";return J++,X}))}function pQ($){return $.replace(/\\n/g,`
60
+ `):$.source,X);return W?{...W,segment:$.displayText}:null}function B_($,Z,J){let Q=Z.length===1?Z[0]:void 0;if(!Q?.heredoc?.quotedDelimiter||Q.fd!==void 0&&Q.fd!==0)return;let X=$.words[0];if(X?.provenance!=="literal"||!N1(X.text))return;if(!$.words.slice(1).every((q)=>q.provenance==="literal"&&q.text.startsWith("-")))return;let Y=Q.heredoc.body,B=a(J.policy,"interpreter.one-liner-paranoid",!!J.paranoidInterpreters);if(J.trace?.recordSegment({type:"interpreter",interpreter:X.text,codeArg:Y,paranoidBlocked:B}),B){let q=T(N("interpreter.one-liner-paranoid",O$),J.policy);if(q)return q}if(!L$(Y,J.scanWork))return null;let W=T(N("interpreter.dangerous-command",k0),J.policy);if(!W)return null;return J.trace?.recordSegment({type:"dangerous-text",token:Y,matched:!0,reason:W.reason}),W}function W_($,Z,J,Q,X){let K=Z.length===1?Z[0]:void 0;if(!K?.heredoc?.quotedDelimiter||K.fd!==void 0&&K.fd!==0)return!1;let Y=u0($.words,X.environment,J.effectiveCwd,Q),B=Y.words.map(S),W=x(B[0]??"");if(Y.unverifiableEnvSplit||!$1.has(W)&&!$1.has(h(W)))return!1;return C1(B)}function q_($,Z,J,Q,X){let K=TJ($,Z.effectiveCwd,Q,J);if(K===null)X?.recordSegment({type:"cwd-change",segment:$.words.map(S).join(" "),effectiveCwdNowUnknown:!0});if(K!==void 0)Z.effectiveCwd=K}function b2($){return{effectiveCwd:$.effectiveCwd,shellGitContextState:uJ($.shellGitContextState),literalHeredocFiles:new Map($.literalHeredocFiles),functionDefinitions:new Map($.functionDefinitions)}}function O3($){let Z=[];for(let J of $){if(!Z.some((Q)=>U_(Q,J)))Z.push(J);if(Z.length>cj)throw new P1}return Z}function U_($,Z){return $.effectiveCwd===Z.effectiveCwd&&I2($.literalHeredocFiles,Z.literalHeredocFiles)&&I2($.functionDefinitions,Z.functionDefinitions)&&I2($.shellGitContextState.effectiveEnvAssignments,Z.shellGitContextState.effectiveEnvAssignments)&&I2($.shellGitContextState.shellAssignments,Z.shellGitContextState.shellAssignments)&&H_($.shellGitContextState.exportedNames,Z.shellGitContextState.exportedNames)&&$.shellGitContextState.allexport===Z.shellGitContextState.allexport&&$.shellGitContextState.keywordExport===Z.shellGitContextState.keywordExport}function I2($,Z){if($===Z)return!0;if(!$||!Z||$.size!==Z.size)return!1;return[...$].every(([J,Q])=>Z.get(J)===Q&&Z.has(J))}function G_($,Z){let J=O4($);return J===void 0?void 0:Z.get(J)}function H_($,Z){return $.size===Z.size&&[...$].every((J)=>Z.has(J))}function j_($,Z){if(!Z)return null;return{reason:Z.reason,segment:$,ruleId:Z.id,intent:Z.intent}}function __($,Z=$.effectiveCwd){let J=Z===null;return{environment:$.environment,cwd:J?void 0:Z??$.cwd,originalCwd:J?void 0:$.cwd,strict:$.strict,paranoid:$.paranoidRm,allowTmpdirVar:$.allowTmpdirVar,protectedGitMetadata:$.protectedGitMetadata,policy:$.policy}}function y9($,Z){let J=T(q2($,Z.scanWork),Z.policy),Q=Z.trace?.currentSegmentIndex??Z.trace?.allocateSegment(),X={type:"dangerous-text",token:$,matched:!!J,reason:J?.reason};if(Z.trace?.recordSegment(X,Q),!J&&/^(?:cd|pushd)\s/.test($))Z.trace?.recordSegment({type:"cwd-change",segment:$,effectiveCwdNowUnknown:!0},Q);return J?{reason:J.reason,segment:$,ruleId:J.id,intent:J.intent}:null}function sJ($,Z){let J={type:"strict-unparseable",rawCommand:$,reason:V0};if(Z.trace?.currentSegmentIndex===void 0)Z.trace?.recordGlobal(J);else Z.trace.recordSegment(J)}function Cz($,Z){return v9($,Z)}function v9($,Z,J,Q){let X=w9($,0,{...Z,...T7(Z),factStore:Q},J);if(!X)return null;return{kind:"deny",reason:X.reason,intent:X.intent??"manual_only",...X.ruleId?{ruleId:X.ruleId}:{},evidence:[{kind:"command",command:$,segment:X.segment}]}}function oJ($,Z,J,Q,X){if(J.kind!=="command")return{toolName:$,input:Z,route:J,context:Q};return{toolName:$,input:Z,route:J,context:Q,command:X}}var u9=[{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"}],N3={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},O_=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],L_=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],h9=[{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"]},...L_.flatMap(($)=>O_.map((Z)=>({id:["secret.home",$.idSlug,Z.slice(1)].join("."),category:"Home path",label:[$.label,Z].join(""),description:["Blocks home ",$.label,Z," credential backup files."].join(""),suffixParts:[...$.directoryParts,[$.basename,Z].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 V3=[{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","/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"]}],tJ=[{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"}],M_=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],g9=tJ.map(($)=>({id:`secret.variant.${$.slug}.separator`,category:"Variant",label:`${$.label}-* / ${$.label}_*`,description:`Blocks ${$.label} variants with dash or underscore suffixes.`,prefix:$.prefix})),k9=tJ.flatMap(($)=>M_.map((Z)=>({id:`secret.variant.${$.slug}.${Z.slice(1)}`,category:"Variant",label:`${$.label}${Z}`,description:`Blocks ${$.label}${Z} private credential variants.`,prefix:$.prefix,suffix:Z}))),f2={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)$/},x9=["agilekeychain","asc","bek","cscfg","fve","gnucash","jks","keychain","kwallet","mdf","ovpn","p12","pcap","pem","pfx","pkcs12","psafe3","rdp","sdf","tblk","tpm"].map(($)=>({id:`secret.ext.${$}`,category:"Extension",label:`.${$}`,description:`Blocks files with the .${$} extension.`,extension:$})),l9=[{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?$/}],eJ=[...u9,N3,...h9,...g9,...k9,f2,...x9,...l9,...V3].map(($)=>({id:$.id,category:$.category,label:$.label,...$.category==="Coding CLI config"?{defaultOff:!0}:{},..."paths"in $?{paths:$.paths}:{description:$.description}})),$Q=new Set(V3.flatMap(($)=>$.category==="Coding CLI config"?[$.id]:[])),F_=eJ.map(($)=>$.id),R3=new Set(F_);import{createRequire as N_}from"node:module";var ZQ=Object.freeze(["hard_stop","use_alternative","scope_down","manual_only","stop_and_explain"]);var P2=64,QQ="Rule config exceeds CC Safety Net's safe source limit.";var JQ=Object.freeze({maxSources:64,concurrency:4,maxRequests:131,maxResponseBytes:67108864});function D3($={}){return{requests:0,responseBytes:0,maxRequests:$.maxRequests??JQ.maxRequests,maxResponseBytes:$.maxResponseBytes??JQ.maxResponseBytes}}function z3($){return{controller:new AbortController,budget:D3(),resolveUrl:$}}function XQ($){if($.requests>=$.maxRequests)throw Error("Rule synchronization exceeds CC Safety Net's safe resource limits.");$.requests++}function KQ($,Z){if(Z>$.maxResponseBytes-$.responseBytes)throw $.responseBytes+=Z,Error("Rule synchronization exceeds CC Safety Net's safe resource limits.");$.responseBytes+=Z}var V_=N_(import.meta.url),YQ,R_=Array(P2+1).fill("over-limit"),BQ=/^[^/]+\/[^/]+$/,D_=/^sha256:[a-f0-9]{64}$/,b3=`must be an integer between ${p3} and ${c3}`,z_=["version","rules","overrides","transparent_wrappers"],b_=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function WQ($){if(!E1($)||!Array.isArray($.rules)||$.rules.length<=P2)return $;return{$schema:$.$schema,version:$.version,rules:R_,overrides:$.overrides,transparent_wrappers:$.transparent_wrappers}}function I_(){let $=V_("../vendor/zod.cjs"),Z=(F)=>{let R=$.superRefine(F);return R._zod.def.when=()=>!0,R},J=$.enum(ZQ),Q=$.union([$.literal("off"),$.looseObject({reason:$.string({error:"required non-empty string"}).min(1,"required non-empty string").max(Y$,`must be at most ${Y$} characters`).describe("Replacement block reason"),intent:J.optional()})],{error:'must be "off" or an object'}).describe("Disable a rule or replace its block reason and intent."),X=$.string({error:"must be a rulebook source string"}).min(1,"must be a non-empty rulebook source string"),K=$.string({error:"must be a command string"}).regex(T0,"must match command pattern").describe("Command name such as 'git', 'docker', or 'rtk'."),Y=$.looseObject({$schema:$.unknown().optional().describe("JSON Schema reference for IDE support"),version:$.literal(1).describe("Schema version (must be 1)"),rules:$.array(X,{error:"must be an array of rulebook source strings"}).max(P2,QQ).default([]).describe("Rulebook source strings such as project-rules or owner/repo#main/team-rules"),overrides:$.record($.string().meta({pattern:BQ.source}),Q).default({}).describe("Rule overrides by id"),transparent_wrappers:$.array(K,{error:"must be an array of command strings"}).default([]).describe("Commands that transparently execute a visible protected child command")}),B=(F,R)=>{if(!E1(F))return;if(Array.isArray(F.rules)&&F.rules.length<=P2){let I=new Set;F.rules.forEach((C,y)=>{if(typeof C!=="string"||C==="")return;if(C.trim()===""){R.addIssue({code:"custom",message:"must be a non-empty rulebook source string",path:["rules",y]});return}let w=m$(C);if(w){R.addIssue({code:"custom",message:w,path:["rules",y]});return}if(I.has(C)){R.addIssue({code:"custom",message:`duplicate rulebook source "${C}"`,path:["rules",y]});return}I.add(C)})}if(E1(F.overrides))for(let I of Object.keys(F.overrides)){if(BQ.test(I))continue;R.addIssue({code:"custom",message:"must use <rulebook-name>/<rule-name>",path:["overrides",I]})}if(!Array.isArray(F.transparent_wrappers))return;let b=new Set;F.transparent_wrappers.forEach((I,C)=>{if(typeof I!=="string"||!T0.test(I))return;if(b.has(I)){R.addIssue({code:"custom",message:`duplicate command "${I}"`,path:["transparent_wrappers",C]});return}if(E7(I)){R.addIssue({code:"custom",message:`reserved command "${I}" cannot be a wrapper`,path:["transparent_wrappers",C]});return}b.add(I)})},W=$.preprocess(WQ,Y.check($.superRefine(B))),q=$.preprocess(WQ,Y.check(Z(B))),U=$.strictObject({fail_closed:$.boolean().optional(),paranoid_rm:$.boolean().optional(),paranoid_interpreters:$.boolean().optional()}),H=(F,R)=>$.intersection($.record($.string().refine((b)=>F.has(b),{error:(b)=>`unknown ${R} rule id "${String(b.input)}"`}),$.unknown()),$.record($.string(),$.enum(["on","off"]))),j=(F)=>$.array($.string({error:"must be a non-empty path string"}),{error:"must be an array of paths"}).check(Z((R,b)=>{if(!Array.isArray(R))return;let I=X$();R.forEach((C,y)=>{if(typeof C!=="string")return;let w=F(C,I);if(w)b.addIssue({code:"custom",message:w,path:[y]})})})),G=$.strictObject({version:$.literal(1),safety:$.strictObject({level:$.enum(["standard","strict","paranoid"]).optional(),overrides:U.optional()}).optional(),workflow:$.strictObject({worktree_mode:$.boolean().optional()}).optional(),destructive_command_protection:$.strictObject({enabled:$.boolean().optional(),overrides:H(s2,"destructive command").optional(),allow_paths:j(n4).optional()}).optional(),secret_protection:$.strictObject({enabled:$.boolean().optional(),overrides:H(R3,"secret protection").optional(),deny_paths:j(a4).optional()}).optional(),audit:$.strictObject({retention_days:$.number({error:b3}).int(b3).min(p3,b3).max(c3,b3).optional().describe("Days of audit log history to keep before the sweep deletes it")}).optional()}),_=(F)=>{let R=(y,w)=>F==="legacy"?y:w,b=R("must match pattern (letters, numbers, hyphens, underscores)","must match command pattern"),I=`required non-empty string up to ${Y$} characters`,C=$.looseObject({name:$.string({error:"required string"}).regex(z1,R("must match pattern (letters, numbers, hyphens, underscores; max 64 chars)","must match rule name pattern")),command:$.string({error:R("required string","required string matching command pattern")}).regex(T0,R(b,"required string matching command pattern")),subcommand:$.string({error:R("must be a string if provided","must match command pattern")}).regex(T0,b).optional(),block_args:$.array($.string({error:R("must be a string","must be a non-empty string")}).refine((y)=>y!=="",{error:R("must not be empty","must be a non-empty string")}),{error:R("required array","required non-empty array")}).refine((y)=>y.length>0,{error:R("must have at least one element","required non-empty array")}),reason:$.string({error:R("required string",I)}).refine((y)=>y!=="",{error:R("must not be empty",I)}).refine((y)=>y.length<=Y$,{error:R(`must be at most ${Y$} characters`,I)}),intent:J.optional()},{error:"must be an object"});return $.array(C,{error:R("must be an array","required array")}).check(Z((y,w)=>{if(!Array.isArray(y))return;let k=new Set;y.forEach((B1,P)=>{let v=E1(B1)?B1.name:void 0;if(typeof v!=="string")return;if(k.has(v.toLowerCase())){w.addIssue({code:"custom",message:`duplicate rule name "${v}"`,path:[P,"name"]});return}k.add(v.toLowerCase())})}))},O=$.looseObject({version:$.literal(1),rules:_("legacy").optional()}),M="required string matching rule name pattern",L=$.looseObject({command:$.string({error:"required non-empty string"}).refine((F)=>F.trim()!=="",{error:"required non-empty string"}),expect:$.enum(["blocked","allowed"]),rule:$.string({error:"must be a string if provided"}).optional()},{error:"must be an object"}).check(Z((F,R)=>{if(!E1(F))return;if(F.expect!=="blocked"||typeof F.rule==="string")return;R.addIssue({code:"custom",message:"required string for blocked fixtures",path:["rule"]})})),D=$.looseObject({name:$.string({error:"required string matching rule name pattern"}).regex(z1,"required string matching rule name pattern"),version:$.string({error:"required non-empty string"}).refine((F)=>F!=="",{error:"required non-empty string"}),allowed_commands:$.array($.string({error:"must match command pattern"}).regex(T0,"must match command pattern"),{error:"required array"}).check(Z((F,R)=>{if(!Array.isArray(F))return;let b=new Set;F.forEach((I,C)=>{if(typeof I!=="string"||!T0.test(I))return;if(b.has(I)){R.addIssue({code:"custom",message:`duplicate command "${I}"`,path:[C]});return}b.add(I)})})),rules:_("rulebook"),tests:$.array(L,{error:"must be an array if provided"}).optional()}).check(Z((F,R)=>{if(!E1(F))return;let b=new Set(m9(F));if(Array.isArray(F.tests)){let C=new Set(F.tests.flatMap((y)=>E1(y)&&y.expect==="blocked"&&typeof y.rule==="string"?[y.rule]:[]));for(let y of C){if(b.has(y))continue;R.addIssue({code:"custom",message:`blocked fixture references unknown rule "${y}"`,path:["tests"]})}}if(!Array.isArray(F.allowed_commands)||!Array.isArray(F.rules))return;let I=new Set(F.allowed_commands.filter((C)=>typeof C==="string"));F.rules.forEach((C,y)=>{let w=E1(C)?C.command:void 0;if(typeof w!=="string"||I.has(w))return;R.addIssue({code:"custom",message:`"${w}" must be listed in allowed_commands`,path:["rules",y,"command"]})})})),z=$.string({error:"required string"}).refine((F)=>F.trim()!=="",{error:"required string"}),f=$.looseObject({spec:z,name:z,version:z,digest:$.string({error:"required sha256 digest"}).regex(D_,"required sha256 digest")},{error:"must be an object"}),A=$.looseObject({rulebooks:$.array($.intersection(f,$.discriminatedUnion("kind",[$.object({kind:$.literal("local-directory"),path:z}),$.object({kind:$.literal("github"),owner:z,repo:z,ref:z,commit:z,path:z,display_ref:$.unknown().optional()})],{error:(F)=>{if(!E1(F.input))return"must be an object";let R=F.input.kind;return typeof R==="string"?`unknown kind "${R}"`:"required string"}})))});return{RulesConfigSchema:W,RulesConfigDiagnosticSchema:q,RuleOverrideSchema:Q,UserPolicySchema:G,LegacyConfigSchema:O,RulebookSchema:D,RulesLockfileSchema:A}}function f$(){return YQ??=I_(),YQ}function qQ(){return f$().RulesConfigSchema}function f_(){return f$().UserPolicySchema}function dz(){return f$().LegacyConfigSchema}function UQ(){return f$().RulebookSchema}function GQ(){return f$().RulesLockfileSchema}function m9($){let Z=E1($)?$.rules:void 0;return(Array.isArray(Z)?Z:[]).flatMap((J)=>{let Q=E1(J)?J.name:void 0;return typeof Q==="string"?[Q]:[]})}function HQ($){let Z=f$().RulesConfigDiagnosticSchema.safeParse($);if(Z.success)return{errors:[],sources:new Set(Z.data.rules)};return{errors:P$(_Q(Z.error.issues,z_)),sources:E_($,Z.error.issues)}}function C2($){let Z=f_().safeParse($);if(Z.success)return[];return P$(_Q(Z.error.issues,b_)," ")}function P$($,Z=": ",J=" "){return[...new Set($.flatMap((Q)=>jQ(Q,Z,J,[])))]}function jQ($,Z,J,Q){let X=[...Q,...$.path],K=A_(X);if($.code==="unrecognized_keys")return $.keys.map((Y)=>`${K?`${K}.`:""}unknown field "${Y}"`);if($.code==="invalid_key")return $.issues.map((Y)=>Y.message);if($.code==="invalid_union"){let Y=$.errors.flat().filter((B)=>B.path.length>0);if(Y.length>0)return Y.flatMap((B)=>jQ(B,Z,J,X))}if(X.length===0)return[$.code==="invalid_type"?"Config must be an object":$.message];if(X.length===1&&($.code==="too_big"||$.code==="too_small")&&$.origin==="array")return[$.message];return[`${K}${X.length===1?J:Z}${P_($)}`]}function P_($){if($.code==="invalid_value")return`must be ${C_($.values)}`;if($.code!=="invalid_type"||!$.message.startsWith("Invalid input:"))return $.message;if($.expected==="object"||$.expected==="record")return"must be an object if provided";return $.expected==="boolean"?"must be a boolean":$.message}function C_($){if($.length>3)return`one of ${$.join(", ")}`;let Z=$.map((J)=>typeof J==="string"?`"${J}"`:String(J));if(Z.length<2)return`${Z[0]}`;return`${Z.slice(0,-1).join(", ")}${Z.length>2?",":""} or ${Z.at(-1)}`}function A_($){return $.map((Z,J)=>{if(typeof Z==="number")return`[${Z}]`;return J===0?String(Z):`.${String(Z)}`}).join("")}function _Q($,Z){let J=$.map((K)=>K.path[1]),Q=[...new Set(J.filter((K)=>typeof K==="string"))],X=(K,Y)=>[K.path.length===0?-1:Z.indexOf(String(K.path[0])),typeof Y==="number"?Y:Q.indexOf(String(Y)),K.code==="custom"?0:1];return $.map((K,Y)=>({issue:K,rank:X(K,J[Y])})).sort((K,Y)=>K.rank[0]-Y.rank[0]||K.rank[1]-Y.rank[1]||K.rank[2]-Y.rank[2]).map((K)=>K.issue)}function E_($,Z){let J=E1($)?$.rules:void 0;if(!Array.isArray(J))return new Set;if(Z.some((X)=>X.path.length===1&&X.path[0]==="rules"))return new Set;let Q=new Set(Z.filter((X)=>X.path[0]==="rules"&&typeof X.path[1]==="number").map((X)=>X.path[1]));return new Set(J.filter((X,K)=>typeof X==="string"&&!Q.has(K)))}function E1($){return!!$&&typeof $==="object"&&!Array.isArray($)}var OQ={version:1,rules:[],overrides:{},transparent_wrappers:[]};function T_($){return HQ($)}function C$($){try{let Z=X0(LQ($));if(Z===null)return{config:null,errors:[]};if(!Z.trim())return{config:null,errors:["Config file is empty"]};let J=JSON.parse(Z),Q=T_(J);if(Q.errors.length>0)return{config:null,errors:Q.errors};let X=qQ().parse(J);return{config:{version:1,rules:X.rules??[],overrides:X.overrides??{},transparent_wrappers:X.transparent_wrappers??[]},errors:[]}}catch(Z){if(Z instanceof u)return{config:null,errors:[Z.message]};let J=Z instanceof Error?Z.message:String(Z);return{config:null,errors:[Z instanceof SyntaxError?"Invalid JSON":J]}}}function oz($){let Z=C$($);if(Z.errors.length>0)return{ok:!1,result:{ok:!1,errors:Z.errors,warnings:[],entries:[]}};return{ok:!0,config:Z.config??OQ}}function tz($,Z=[]){I3($,{version:1,rules:Z,overrides:{},transparent_wrappers:[]})}function ez($,Z="project-rules"){I3($,{rulebook_version:1,name:Z,version:"1.0.0",description:Z==="project-rules"?"Project-specific CC Safety Net rules.":"User-specific CC Safety Net rules.",author:Z==="project-rules"?"project":"user",allowed_commands:["docker"],rules:[{name:"block-docker-system-prune",command:"docker",subcommand:"system",block_args:["prune"],reason:"Use targeted cleanup instead."}],tests:[{command:"docker system prune",expect:"blocked",rule:"block-docker-system-prune"}]})}function I3($,Z,J,Q){GZ(LQ($),`${JSON.stringify(Z,null,2)}
61
+ `,J,Q)}function LQ($){return typeof $==="string"?u2($):$}import{chmodSync as S_,existsSync as p9,mkdirSync as y_,readFileSync as c9}from"node:fs";import{dirname as NQ,join as w_}from"node:path";var v_=new Set(["standard","strict","paranoid"]),P3={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:[]},audit:{retention_days:p2}};function T$($){return w_(NQ(K0($)),x2)}function Hb($={}){let Z=T$($);if(!p9(Z))return{path:Z,exists:!1,raw:"",policy:A$(),errors:[]};let J=c9(Z,"utf-8");if(!J.trim())return{path:Z,exists:!0,raw:J,policy:A$(),errors:["Config file is empty"]};try{let Q=JSON.parse(J),X=C2(Q);return{path:Z,exists:!0,raw:J,policy:X.length>0?A$():E$(Q),errors:X}}catch(Q){return{path:Z,exists:!0,raw:J,policy:A$(),errors:[`Invalid JSON: ${Q instanceof Error?Q.message:String(Q)}`]}}}function f3($,Z={}){let J=T$(Z),Q=C2($),X=Q.length>0?A$():E$($);if(Q.length>0)return{path:J,policy:X,errors:Q};return y_(NQ(J),{recursive:!0,mode:448}),I3(J,X,384),S_(J,384),{path:J,policy:X,errors:[]}}function jb($){let Z=C2($);if(Z.length>0)return{errors:Z};return{preview:u_(E$($)),errors:[]}}function u_($){let Z=c4({safety:DQ($.safety)}),J=n3({destructiveCommandProtectionEnabled:$.destructive_command_protection.enabled,destructiveCommandRuleOverrides:$.destructive_command_protection.overrides},Z.capabilities),Q=Object.values(J),X=Q.filter((Y)=>Y.source!=="catastrophic"),K=Object.values($.destructive_command_protection.overrides);return{selectedPreset:$.safety.level,effectiveLevel:Z.effectiveLevel,capabilities:Z.capabilities,rules:J,counts:{enabled:X.filter((Y)=>Y.enabled).length,disabled:X.filter((Y)=>!Y.enabled).length,explicitOn:K.filter((Y)=>Y==="on").length,explicitOff:K.filter((Y)=>Y==="off").length,effectiveCustomizations:Q.filter((Y)=>Y.changesInherited).length,inheritedRequiresStrict:Q.filter((Y)=>!Y.enabled&&!Y.override&&Y.activationCapability==="fail_closed").length,inheritedRequiresParanoid:Q.filter((Y)=>!Y.enabled&&!Y.override&&(Y.activationCapability==="paranoid_rm"||Y.activationCapability==="paranoid_interpreters")).length}}}function _b($={}){let Z=T$($);if(!p9(Z))return f3(P3,$);let J=c9(Z,"utf-8");if(!J.trim())return f3(P3,$);try{return f3(E$(JSON.parse(J)),$)}catch{return f3(P3,$)}}function VQ($={}){let Z=k_(T$($));return{safety:Z.policy.safety,worktreeMode:Z.policy.worktreeMode,destructiveCommandProtectionEnabled:Z.policy.destructiveCommandProtectionEnabled,destructiveCommandRuleOverrides:{...Z.policy.destructiveCommandRuleOverrides},destructiveCommandAllowPaths:[...Z.policy.destructiveCommandAllowPaths],secretProtection:Z.policy.secretProtection,errors:Z.errors,...Z.fallback?{fallback:Z.fallback}:{}}}function E$($){if(!J0($))return A$();let Z=J0($.safety)?$.safety:{},J=J0(Z.overrides)?Z.overrides:{},Q=J0($.workflow)?$.workflow:{},X=J0($.destructive_command_protection)?$.destructive_command_protection:{},K=J0($.secret_protection)?$.secret_protection:{};return{version:1,safety:{level:v_.has(Z.level)?Z.level:"standard",overrides:{...typeof J.fail_closed==="boolean"?{fail_closed:J.fail_closed}:{},...typeof J.paranoid_rm==="boolean"?{paranoid_rm:J.paranoid_rm}:{},...typeof J.paranoid_interpreters==="boolean"?{paranoid_interpreters:J.paranoid_interpreters}:{}}},workflow:{worktree_mode:typeof Q.worktree_mode==="boolean"?Q.worktree_mode:!1},destructive_command_protection:{enabled:typeof X.enabled==="boolean"?X.enabled:!0,overrides:MQ(X.overrides,s2),allow_paths:g_(X.allow_paths)},secret_protection:{enabled:typeof K.enabled==="boolean"?K.enabled:!0,overrides:MQ(K.overrides,R3),deny_paths:h_(K.deny_paths)},audit:{retention_days:c2(J0($.audit)?$.audit.retention_days:void 0)}}}function MQ($,Z){if(!J0($))return{};return Object.fromEntries(Object.entries($).flatMap(([J,Q])=>Z.has(J)&&(Q==="on"||Q==="off")?[[J,Q]]:[]))}function h_($){if(!Array.isArray($))return[];let Z=X$();return $.filter((J)=>a4(J,Z)===null)}function g_($){if(!Array.isArray($))return[];let Z=X$();return $.filter((J)=>n4(J,Z)===null)}function J0($){return!!$&&typeof $==="object"&&!Array.isArray($)}function A$(){return structuredClone(P3)}function k_($){let Z=x_();if(!p9($)){let J=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!J0(J))return{policy:Z,errors:[]};return{policy:FQ(E$(J)),errors:[]}}try{let J=c9($,"utf-8");if(!J.trim())return{policy:Z,errors:[`${$}: Config file is empty`],fallback:"defaults"};let Q=JSON.parse(J),X=C2(Q),K=FQ(E$(Q));if(X.length>0)return{policy:K,errors:X.map((Y)=>`${$}: ${Y}`),fallback:J0(Q)?"salvaged":"defaults"};return{policy:K,errors:[]}}catch(J){let Q=J instanceof Error?J.message:String(J);return{policy:Z,errors:[`${$}: ${J instanceof SyntaxError?"Invalid JSON":Q}`],fallback:"defaults"}}}function RQ($){let Z=Object.entries($),J=new Set(Z.flatMap(([Q,X])=>X==="on"?[Q]:[]));return new Set([...[...$Q].filter((Q)=>!J.has(Q)),...Z.flatMap(([Q,X])=>X==="off"?[Q]:[])])}function x_(){return{safety:{},worktreeMode:!1,destructiveCommandProtectionEnabled:!0,destructiveCommandRuleOverrides:{},destructiveCommandAllowPaths:[],secretProtection:{enabled:!0,disabledRules:RQ({}),denyPaths:[]}}}function FQ($){return{safety:DQ($.safety),worktreeMode:$.workflow.worktree_mode,destructiveCommandProtectionEnabled:$.destructive_command_protection.enabled,destructiveCommandRuleOverrides:{...$.destructive_command_protection.overrides},destructiveCommandAllowPaths:[...$.destructive_command_protection.allow_paths],secretProtection:{enabled:$.secret_protection.enabled,disabledRules:RQ($.secret_protection.overrides),denyPaths:[...$.secret_protection.deny_paths]}}}function DQ($){return{level:$.level,overrides:{failClosed:$.overrides.fail_closed,paranoidRm:$.overrides.paranoid_rm,paranoidInterpreters:$.overrides.paranoid_interpreters}}}import{dirname as d9}from"node:path";var fQ="This path contains the protected policy config and you must not modify or delete it.",l_=new Set(["[","cat","file","grep","head","jq","less","ls","more","rg","sed","stat","tail","test","wc"]);function PQ($){let Z=y0(B0()),J=s_($.invocation.context.executionCwd,Z);if($.invocation.route.kind==="patch")return zQ($.paths.map((X)=>X.raw),!1,$.invocation.context.executionCwd,J,Z);let Q=_1($,"input-candidate");if($.invocation.route.kind==="command")return Q?bQ(Q.shell,$.invocation.context.executionCwd,J,Z):null;if($.invocation.route.kind==="unknown"&&Q){let X=bQ(Q.shell,$.invocation.context.executionCwd,J,Z);if(X)return X}return zQ($.paths.map((X)=>X.raw),$.invocation.route.kind==="grep"||$.invocation.route.kind==="glob"||t2($.invocation.toolName),$.invocation.context.executionCwd,J,Z)}function zQ($,Z,J,Q,X){if(Z)return null;let K=$.find((Y)=>A2(Y,J,Q,X));return K?{target:K}:null}function bQ($,Z,J,Q){let X=P4($,Z,Q,{findSegmentTarget:(K,Y)=>m_(K,Y,J,Q)?.target??null,isRedirectionTarget:(K,Y)=>A2(K,Y.cwd,J,Q),findMalformedTarget:(K)=>i_(K,Z,J,Q)?.target??null,normalizeCwd:K1});return X?{target:X}:null}function m_($,Z,J,Q){if(Z2($))return null;let X=Q.environment,K=I1([...$],X),Y=h(K[0]??"").toLowerCase(),B=K.slice(1);if(Y==="rm"&&p_(B)){let W=c_(B).find((q)=>IQ(L1(q,Z.variables),Z.cwd,J,Q));if(W)return{target:W}}if(Y==="find"){if($3(K,1)||Z9(K,X)){let q=(e4(g(K))??g(["."])).find((U)=>{let H=L1(U.text,Z.variables);return A2(H,Z.cwd,J,Q)||IQ(H,Z.cwd,J,Q)})?.text;if(q)return{target:q}}}if(Y==="mv"){let W=C4(B).sources.find((q)=>r_(L1(q,Z.variables),Z.cwd,J,Q));if(W)return{target:W}}if(d_($,X))return null;for(let W of $)for(let q of CQ(W))if(A2(L1(q,Z.variables),Z.cwd,J,Q))return{target:q};return null}function p_($){return $.some((Z)=>Z==="--recursive"||Z.startsWith("-")&&!Z.startsWith("--")&&/[rR]/.test(Z.slice(1)))}function c_($){let Z=$.indexOf("--");if(Z!==-1)return[...$.slice(0,Z).filter((J)=>!J.startsWith("-")),...$.slice(Z+1)];return $.filter((J)=>!J.startsWith("-"))}function d_($,Z){let J=I1([...$],Z);if(J.length===0)return!1;let Q=h(J[0]??"").toLowerCase();if(!l_.has(Q))return!1;if(Q!=="sed")return!0;return!J.slice(1).some((X)=>X.startsWith("-i")||X==="--in-place"||X.startsWith("--in-place="))}function i_($,Z,J,Q){for(let X of $.split(/\s+/))for(let K of CQ(X))if(A2(K,Z,J,Q))return{target:K};return null}function CQ($){let Z=$.trim().replace(/^['"]|['"]$/g,""),J=Z.indexOf("=");return J===-1||J===Z.length-1?[Z]:[Z,Z.slice(J+1)]}function s_($,Z){let J=K1(T$(),$,Z),Q=d9(J),X=new Set;for(let K=Q;;K=d9(K))if(X.add(S$(K)),d9(K)===K)break;return{file:S$(J),directory:S$(Q),directoryAndAncestors:X}}function A2($,Z,J,Q){return S$(K1($,Z,Q))===J.file}function IQ($,Z,J,Q){return J.directoryAndAncestors.has(S$(K1($,Z,Q)))}function r_($,Z,J,Q){let X=S$(K1($,Z,Q));return X===J.file||J.directoryAndAncestors.has(X)}function S$($){return process.platform==="win32"?$.toLowerCase():$}import{homedir as n_}from"node:os";import{isAbsolute as s9,resolve as hQ}from"node:path";import{fileURLToPath as a_}from"node:url";var gQ="Access to a sensitive path is not allowed.",kQ=new Set(["echo","printf"]),o_=new Set(["find"]),t_=new Set(["-exec","-execdir"]),e_=new Set([";","+"]),$O=new Set(["-delete","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),ZO=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-samefile"]),JO=new Set(["python","python2","python3","node","deno","bun","ruby","perl","php","rscript","osascript","bash","sh","zsh","dash","ksh"]),QO=new Set(["node","bun"]),XO=new Set(["bun","child_process","deno","dotenv","fs","subprocess"]),KO=new Set(["append","awk","base64","cat","chmod","chown","connect","copy","cp","database","dd","eval","exec","fetch","file","function","grep","head","include","load","move","mv","open","popen","read","remove","rename","require","rg","rm","sed","shell","source","spawn","strings","system","tail","tar","truncate","unlink","write","xxd","zip"]),xQ=new Set(["-c","-e","-r","-E","--eval","--exec"]),YO=new Set(["src/cli/cc-safety-net.ts","dist/bin/cc-safety-net.js"]),BO=new Map([["c",new Set(["bash","sh","zsh","dash","ksh","python"])],["e",new Set(["node","deno","bun","ruby","perl","rscript","osascript"])],["E",new Set(["perl"])],["r",new Set(["php"])]]),WO=new Set(["grep","rg"]),AQ="f",EQ="file",qO="files",UO=new Set(["e","f"]),GO=new Set(["regexp","file"]),HO=new Set(["e","f","A","B","C","m"]),jO=new Set(["regexp","file","after-context","before-context","context","max-count"]),_O=new Set(["|","|&"]),i9="__CC_SAFETY_NET_PIPE_INPUT__",lQ=new Set(["bash","sh","zsh","dash","ksh"]),OO=new Map([["bash",new Set(["-O"])],["sh",new Set(["-O"])],["zsh",new Set(["-o"])],["dash",new Set(["-o"])],["ksh",new Set(["-o"])],["python",new Set(["-W","-X"])],["node",new Set(["-r","--require","--loader","--import","--input-type"])]]);function TQ($,Z,J,Q,X){let K=d$();for(let Y of $){if(eO(Y,Z,J?.denyPaths??[],Q,K))return{target:Y,ruleId:"secret.deny-path"};if(X&&!X.has(Y))continue;let B=oO(Y,Z,J,K);if(B)return{target:Y,ruleId:B}}return null}function mQ($,Z,J={}){let Q=SQ($),X=TQ(Q,$.invocation.context.executionCwd,Z,$.invocation.context.configCwd),K=X?.ruleId!=="secret.deny-path"&&J.strict===!1?SQ($,{refineJavaScriptInlineData:!0}):Q,Y=K.length===Q.length?X:TQ(Q,$.invocation.context.executionCwd,Z,$.invocation.context.configCwd,new Set(K));if(Y?.ruleId!=="secret.deny-path"&&J.strict===!1&&LO($))return null;return Y}function LO($){if($.invocation.route.kind!=="command")return!1;let Z=_1($,"input-candidate")??_1($,"declared-command");if(!Z)return!1;if(Z.program.nodes.some((Y)=>Y.kind==="command"&&Y.nested.length>0))return!1;let J=[];for(let Y of Z.shell.entries){if(Y.kind==="operator"&&Y.boundary)return!1;if(Y.kind==="redirection")return!1;if(Y.kind!=="operator")J.push(d1(Y.text))}let Q=w$(J);if(Q.length===0)return!1;let X=o0(Q[0]??"").toLowerCase(),K=Q.slice(1);if(X==="test")return K.length===2&&(K[0]==="-e"||K[0]==="-f");if(X!=="find")return!1;return!K.some((Y)=>$O.has(Y))}function SQ($,Z={}){if($.invocation.route.kind==="command"){let Q=_1($,"input-candidate");return Q?S2(Q.shell,$.store,Z):[]}if($.invocation.route.kind!=="unknown")return $.paths.map((Q)=>Q.raw);let J=_1($,"input-candidate");return[...J?S2(J.shell,$.store,Z):[],...$.paths.map((Q)=>Q.raw)]}function S2($,Z,J){if($.status==="structural-limit")throw new z0;if($.status==="unclosed-quote")return[];if($.status==="invalid")throw Error("Unable to parse command for secret protection");let Q=[...$.assignmentFallbacks,...uO(d1($.source),Z,J)],X=[],K=null;for(let Y of $.entries){if(Y.kind==="operator"){if(!Y.boundary)continue;if(X.length>0){if(Q.push(...C3(X,Z,J)),K!==null)Q.push(...yQ(K,X,Z,J));K=_O.has(Y.operator)?X:null,X=[]}else K=null;continue}if(Y.kind==="redirection"){let B=Y.target?d1(Y.target):void 0;if(B&&Y.targetOrder==="legacy-segment")X.push(B);else if(B)Q.push(B);continue}X.push(d1(Y.text))}if(X.length>0){if(Q.push(...C3(X,Z,J)),K!==null)Q.push(...yQ(K,X,Z,J))}return Q}function C3($,Z,J){let Q=fO($),X=w$($);if(X.length===0)return Q;let K=X[0]??"",Y=o0(K).toLowerCase(),B=X.slice(1),W=MO(K,Y,B);if(W)return[...Q,...W];if(kQ.has(Y))return Q;if(WO.has(Y))return[...Q,...cO(B)];if(o_.has(Y))return[...Q,...PO(B,Z,J)];if(F1.has(Y))return[...Q,...B.flatMap((q)=>wQ("awk",q)),...B.flatMap((q)=>AO(q,Z,J)),...B.flatMap(EO)];if(dQ(Y)){if(lQ.has(Y)){let q=Y7(Y,B);if(q!==null&&Z.getShellSyntax(q).status==="structural-limit")throw new z0}return[...Q,...CO(Y,B,J)]}return[...Q,...B.flatMap((q)=>wQ(Y,q))]}function MO($,Z,J){let Q=Z==="cc-safety-net"&&J[0]==="explain",X=(Z==="bun"||Z==="node")&&FO(J[0])&&J[1]==="explain";if(!Q&&!X)return null;let K=X?[$,J[0]??""]:[$],Y=J.slice(X?2:1);for(let B=0;B<Y.length;B++){let W=Y[B];if(W==="--json"||W==="--help"||W==="-h")continue;if(W==="--cwd"){let q=Y[B+1];if(q&&!q.startsWith("--"))K.push(q);B++;continue}return K}return K}function FO($){let Z=$?.replaceAll("\\","/");return[...YO].some((J)=>Z===J||Z?.endsWith(`/${J}`))}function yQ($,Z,J,Q){if(zO(Z,J,Q))return NO($);let X=bO(Z);if(X===null)return[];return VO($).flatMap((K)=>lQ.has(X)?S2(J.getShellSyntax(K),J,Q):sQ(K))}function NO($){let Z=w$($);if(Z.length===0)return[];let J=o0(Z[0]??"").toLowerCase();if(!kQ.has(J))return[];return Z.slice(1)}function VO($){let Z=w$($);if(Z.length===0)return[];let J=o0(Z[0]??"").toLowerCase(),Q=Z.slice(1);if(J==="echo"){let X=Q.findIndex((K)=>!/^-[neE]+$/.test(K));return[(X===-1?[]:Q.slice(X)).join(" ")]}if(J==="printf")return RO(Q);return[]}function RO($){let Z=$[0];if(Z===void 0)return[];let J=(Z.match(/%%|%[bqs]/g)??[]).filter((X)=>X!=="%%").length;if(J===0||$.length===1)return[pQ(Z)];let Q=$.slice(1);return Array.from({length:Math.ceil(Q.length/J)},(X,K)=>DO(Z,Q.slice(K*J,(K+1)*J)))}function DO($,Z){let J=0;return pQ($.replace(/%%|%[bqs]/g,(Q)=>{if(Q==="%%")return"%";let X=Z[J]??"";return J++,X}))}function pQ($){return $.replace(/\\n/g,`
62
62
  `).replace(/\\t/g,"\t").replace(/\\r/g,"\r")}function zO($,Z,J){let Q=w$($);if(Q.length===0||o0(Q[0]??"").toLowerCase()!=="xargs")return!1;let X=i0(Q),K=Q.slice(X.childStart);if(K.length===0)return!1;if(X.replacementToken==="")return!1;let Y=X.replacementToken,B=Y===null?[...K,i9]:K.map((W)=>W.split(Y).join(i9));return C3(B,Z,J).some((W)=>W.includes(i9))}function bO($){let Z=w$($);if(Z.length===0)return null;let J=o0(Z[0]??"").toLowerCase();if(!dQ(J))return null;return IO(J,Z.slice(1))?J:null}function IO($,Z){let J=cQ($);for(let Q=0;Q<Z.length;Q++){let X=Z[Q];if(X===void 0)break;if(xQ.has(X)||iQ($,X)||/^--(?:eval|exec)=/.test(X))return!1;if(X==="-")return!0;if(X.startsWith("-")){if(J==="python"&&X==="-m")return!1;if(OO.get(J)?.has(X))Q++;continue}return!1}return!0}function cQ($){return/^python\d/.test($)?"python":$}function fO($){let Z=[];for(let J of $){if(aQ(J))continue;let Q=/^[A-Za-z_][A-Za-z0-9_]*=(.*)$/.exec(J);if(Q===null)break;if(Q[1]!==void 0&&Q[1]!=="")Z.push(Q[1])}return Z}function wQ($,Z){if(Z==="--")return[];let J=[],Q=Z.indexOf("=");if(Q>0&&Q<Z.length-1)J.push(Z.slice(Q+1));if(Z.startsWith("-"))return J;if($==="tar"&&/\.(?:tar|tgz|tar\.gz|zip)$/i.test(Z))return J;if($==="zip"&&/\.zip$/i.test(Z))return J;return J.push(Z),J}function PO($,Z,J){let Q=$.findIndex((K)=>K.startsWith("-")||K==="("||K==="!"||K===";"),X=[...$.slice(0,Q===-1?$.length:Q)];for(let K=0;K<$.length;K++){if(!t_.has($[K]??""))continue;let Y=$.slice(K+1),B=Y.findIndex((U)=>e_.has(U)),W=B===-1?Y:Y.slice(0,B),q=C3(W,Z,J);if(X.push(...q.filter((U)=>U!=="{}")),!q.includes("{}"))continue;X.push(...$.slice(0,K).flatMap((U,H,j)=>{if(!ZO.has(U))return[];let G=j[H+1];return G===void 0?[]:[G,G.replace(/^\*+\//,"").replace(/\/\*+$/g,"").replace(/^\*+/,"").replace(/\*+$/g,"")]}))}return X}function dQ($){return JO.has($)||/^python\d/.test($)}function CO($,Z,J){let Q=[];for(let X=0;X<Z.length;X++){let K=Z[X];if(K===void 0)break;if(xQ.has(K)||iQ($,K)){let B=Z[X+1];if(B!==void 0)Q.push(...vQ($,B,J)),X++;continue}let Y=/^--(?:eval|exec)=(.*)$/.exec(K);if(Y!==null&&Y[1]!==void 0){Q.push(...vQ($,Y[1],J));continue}if(!K.startsWith("-"))Q.push(K)}return Q}function iQ($,Z){if(!Z.startsWith("-")||Z.startsWith("--")||Z.length<=2)return!1;return BO.get(Z[Z.length-1]??"")?.has(cQ($))??!1}function AO($,Z,J){if(!$.includes("system"))return[];return h6($)?.commands.flatMap((Q)=>S2(Z.getShellSyntax(Q),Z,J))??[]}function EO($){return Array.from($.matchAll(/\bgetline(?:\s+[A-Za-z_][A-Za-z0-9_]*)?\s*<\s*"((?:\\.|[^"\\])*)"/g)).map((Z)=>Z[1]).filter((Z)=>Z!==void 0&&Z!=="")}function sQ($){let Z=Array.from($.matchAll(/(['"`])((?:\\.|(?!\1).)*)\1/g)).map((Q)=>Q[2]).filter((Q)=>Q!==void 0&&Q!==""),J=($.match(/[\w./~@+-]*[./~][\w./~@+-]*/g)??[]).filter((Q)=>Q!=="process.versions.sqlite"||Z.some((X)=>X.includes(Q)));return[...Z,...Z.flatMap(rQ),...J]}function vQ($,Z,J){let Q=sQ(Z);if(!J.refineJavaScriptInlineData||!QO.has($)||Q.length===0)return Q;let X=TO(Z);return X!==null&&!yO(X)?[]:Q}function TO($){let Z=$.split("");for(let J=0;J<$.length;J++){let Q=$[J];if(Q!=="'"&&Q!=='"'&&Q!=="`")continue;if(Q==="`"&&SO($,J))return null;Z[J]=" ";let X=!1;for(let K=J+1;K<$.length;K++){let Y=$[K];if(Z[K]=" ",Y==="\\"){if(K++,K<$.length)Z[K]=" ";continue}if(Q==="`"&&Y==="$"&&$[K+1]==="{")return null;if(Q!=="`"&&(Y===`
63
63
  `||Y==="\r"))return null;if(Y!==Q)continue;J=K,X=!0;break}if(!X)return null}return Z.join("")}function SO($,Z){for(let J=Z-1;J>=0;J--){let Q=$[J];if(!Q||/\s/.test(Q))continue;return/[\w$\])]/.test(Q)}return!1}function yO($){for(let Z of $.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let J=Z[0],Q=Z.index;if(XO.has(J.toLowerCase()))return!0;let X=J.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((K)=>K.toLowerCase());if(!X.some((K)=>KO.has(K)))continue;if(X.length>1)return!0;if(wO($,Q)===".")return!0;if(vO($,Q+J.length)==="(")return!0}return!1}function wO($,Z){for(let J=Z-1;J>=0;J--)if(!/\s/.test($[J]??""))return $[J];return}function vO($,Z){for(let J=Z;J<$.length;J++)if(!/\s/.test($[J]??""))return $[J];return}function uO($,Z,J){return lO($).flatMap((Q)=>{let X=Z.getShellSyntax(Q);if(X.status==="invalid")return[];return[...S2(X,Z,J),...hO(X)?gO(X):[]]})}function hO($){let Z=$.entries;for(let J=0;J<Z.length;J++){let Q=Z[J];if(Q?.kind!=="word"||o0(d1(Q.text)).toLowerCase()!=="base64")continue;for(let X=J+1;X<Z.length;X++){let K=Z[X];if(K?.kind==="operator")break;if(K?.kind!=="word")continue;let Y=d1(K.text);if(Y==="--decode"||!Y.startsWith("--")&&Y.startsWith("-")&&/[dD]/.test(Y))return!0}}return!1}function gO($){return $.entries.flatMap((Z)=>Z.kind==="word"?[d1(Z.text)]:Z.kind==="redirection"&&Z.target?[d1(Z.target)]:[]).flatMap(rQ)}function rQ($){let Z=xO($);if(Z===null)return[];let J=Buffer.from(Z,"base64").toString("utf8");if(J===""||kO(J))return[];return Buffer.from(J,"utf8").toString("base64").replace(/=+$/g,"")===Z.replace(/=+$/g,"")?[J]:[]}function kO($){return Array.from($).some((Z)=>{let J=Z.charCodeAt(0);return J<32||J===127})}function xO($){if($.length<8||!/^[A-Za-z0-9+/_-]+={0,2}$/.test($))return null;if(/=/.test($.replace(/=+$/g,"")))return null;let Z=$.replace(/=+$/g,"");if(Z.length%4===1)return null;return`${Z.replace(/-/g,"+").replace(/_/g,"/")}${"=".repeat((4-Z.length%4)%4)}`}function lO($){let Z=[],J={inSingle:!1,inDouble:!1,escaped:!1};for(let Q=0;Q<$.length;Q++){let X=$[Q];if(!X)break;if(r$(X,J))continue;if(nQ($,Q,J)){let K=mO($,Q+1);if(K!==null)Z.push(K.body),Q=K.endIndex;continue}if(!J.inSingle&&X==="`"){let K=pO($,Q);if(K!==null)Z.push(K.body),Q=K.endIndex}}return Z}function mO($,Z){let J={inSingle:!1,inDouble:!1,escaped:!1},Q=1;for(let X=Z+1;X<$.length;X++){let K=$[X];if(!K)break;if(r$(K,J))continue;if(nQ($,X,J)){Q++,X++;continue}if(!J.inSingle&&!J.inDouble&&K===")"){if(Q--,Q===0)return{body:$.slice(Z+1,X),endIndex:X}}}return null}function pO($,Z){let J=!1;for(let Q=Z+1;Q<$.length;Q++){let X=$[Q];if(!X)break;if(J){J=!1;continue}if(X==="\\"){J=!0;continue}if(X==="`")return{body:$.slice(Z+1,Q),endIndex:Q}}return null}function nQ($,Z,J){return!J.inSingle&&$[Z]==="$"&&$[Z+1]==="("&&$[Z+2]!=="("}function cO($){let Z=[],J=[],Q=!1,X=!1,K=!1;for(let W=0;W<$.length;W++){let q=$[W];if(q===void 0)break;if(!K&&q==="--"){K=!0;continue}if(K){J.push(q);continue}let U=/^--([^=]+)(?:=(.*))?$/.exec(q);if(U!==null){let H=U[1]??"",j=U[2];if(H===qO)X=!0;if(GO.has(H))Q=!0;if(j!==void 0){if(H===EQ)Z.push(j);continue}if(jO.has(H)){let G=$[W+1];if(H===EQ&&G!==void 0)Z.push(G);W++}continue}if(q.startsWith("-")&&q.length>1){let H=q.slice(1),j="",G="";for(let _=0;_<H.length;_++){let O=H[_]??"";if(UO.has(O))Q=!0;if(HO.has(O)){j=O,G=H.slice(_+1);break}}if(j!=="")if(G.length>0){if(j===AQ)Z.push(G)}else{let _=$[W+1];if(j===AQ&&_!==void 0)Z.push(_);W++}continue}J.push(q)}let B=!Q&&!X?J.slice(1):J;return[...Z,...B]}function w$($){let Z=$.findIndex((J)=>!aQ(J)&&!/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(J));return Z===-1?[]:[...$.slice(Z)]}function aQ($){return $==="env"||$==="command"||$==="builtin"||$==="sudo"}var dO=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),iO=".env.",sO=new Set([".env.example",".env.sample",".env.template",".env.defaults"]),rO=[".env.example.",".env.sample."],nO=new Set(["node_modules","__pycache__"]),aO=[["vendor","bundle"],["vendor","cache"]];function oO($,Z,J,Q){let X=L0($,Z,Q);if(!X)return null;let K=e(X.split("/").pop()??""),Y=e(X);if(sO.has(K)||rO.some((q)=>K.startsWith(q)))return null;for(let q of h9){let U=q.suffixParts.join("/");if((Y===`~/${U}`||Y.startsWith(`~/${U}/`))&&O0(q.id,J))return q.id}let B=tO(X,Z,J,Q);if(B)return B;if(dO.has(K))return null;for(let q of u9)if(K===q.basename&&O0(q.id,J))return q.id;if(K.startsWith(iO)&&O0(N3.id,J))return N3.id;for(let q of g9)if(K.length>q.prefix.length&&K.startsWith(q.prefix)){let U=K.slice(q.prefix.length)[0];if((U==="-"||U==="_")&&O0(q.id,J))return q.id}for(let q of k9)if(K.length>q.prefix.length&&K.startsWith(q.prefix)){if(K.slice(q.prefix.length)===q.suffix&&O0(q.id,J))return q.id}if($L(Y))return null;if(!K.includes(".")&&f2.pattern.test(K)&&O0(f2.id,J))return f2.id;let W=ZL(K,J);if(W)return W;return null}function tO($,Z,J,Q){return V3.find((X)=>{if(!O0(X.id,J))return!1;switch(X.id){case"secret.cli.claude-code":return d($,s(process.env.CLAUDE_CONFIG_DIR,"~/.claude",Z,Q),[".credentials.json"]);case"secret.cli.claude-code.config":{let K=e($).split("/");return d($,s(process.env.CLAUDE_CONFIG_DIR,"~/.claude",Z,Q),["settings.json","settings.local.json"])||T2($,"~/.claude.json",Z,Q)||K.at(-1)==="settings.local.json"&&K.at(-2)===".claude"||K.at(-1)===".mcp.json"}case"secret.cli.antigravity":return d($,L0("~/.gemini/config",Z,Q),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let K=s(process.env.CODEX_HOME,"~/.codex",Z,Q);return d($,K,["auth.json",".credentials.json"])||E2($,K,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let K=s(process.env.CODEX_HOME,"~/.codex",Z,Q),Y=e($).split("/").at(-1)??"";return d($,K,["config.toml"])||Y.endsWith(".config.toml")&&d($,K,[Y])}case"secret.cli.gemini":return d($,Y1(s(process.env.GEMINI_CLI_HOME,"~",Z,Q),".gemini"),["oauth_creds.json","mcp-oauth-tokens.json","a2a-oauth-tokens.json","gemini-credentials.json"]);case"secret.cli.gemini.config":{let K=e($).split("/"),Y=process.env.ProgramData?[Y1(s(process.env.ProgramData,"",Z,Q),"gemini-cli")]:[];return d($,Y1(s(process.env.GEMINI_CLI_HOME,"~",Z,Q),".gemini"),["settings.json","google_accounts.json"])||K.at(-1)==="settings.json"&&K.at(-2)===".gemini"||(process.env.GEMINI_CLI_SYSTEM_SETTINGS_PATH?.trim()?T2($,process.env.GEMINI_CLI_SYSTEM_SETTINGS_PATH,Z,Q):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...Y].some((B)=>d($,L0(B,Z,Q),["settings.json"]))}case"secret.cli.copilot-cli":{let K=s(process.env.COPILOT_HOME,"~/.copilot",Z,Q);return d($,K,["config.json"])||E2($,K,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return d($,s(process.env.COPILOT_HOME,"~/.copilot",Z,Q),["mcp-config.json"]);case"secret.cli.kimi-code":{let K=s(process.env.KIMI_CODE_HOME,"~/.kimi-code",Z,Q),Y=s(process.env.KIMI_SHARE_DIR,"~/.kimi",Z,Q);return d($,K,["server.token"])||E2($,K,["credentials"])||E2($,Y,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let K=["config.toml","mcp.json"],Y=e($).split("/");return Y.at(-1)==="mcp.json"&&Y.at(-2)===".kimi-code"||d($,s(process.env.KIMI_CODE_HOME,"~/.kimi-code",Z,Q),K)||d($,s(process.env.KIMI_SHARE_DIR,"~/.kimi",Z,Q),[...K,"config.json","config.json.bak"])}case"secret.cli.opencode":{let K=Y1(s(process.env.XDG_DATA_HOME,"~/.local/share",Z,Q),"opencode"),Y=e($).split("/").at(-1)??"",B=process.env.OPENCODE_DB?.trim(),W=B&&B!==":memory:"?[B,`${B}-wal`,`${B}-shm`]:[];return d($,K,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(Y)&&d($,K,[Y])||W.some((q)=>T2($,q,Z,Q))}case"secret.cli.opencode.config":{let K=process.env.OPENCODE_CONFIG_DIR?s(process.env.OPENCODE_CONFIG_DIR,"~/.config/opencode",Z,Q):Y1(s(process.env.XDG_CONFIG_HOME,"~/.config",Z,Q),"opencode"),Y=process.env.ProgramData?[Y1(s(process.env.ProgramData,"",Z,Q),"opencode")]:[],B=["opencode.json","opencode.jsonc"];return B.includes(e($).split("/").at(-1)??"")||d($,K,B)||(process.env.OPENCODE_CONFIG?.trim()?T2($,process.env.OPENCODE_CONFIG,Z,Q):!1)||["/Library/Application Support/opencode","/etc/opencode",...Y].some((W)=>d($,L0(W,Z,Q),B))}case"secret.cli.pi":return d($,s(process.env.PI_CODING_AGENT_DIR,"~/.pi/agent",Z,Q),["auth.json"]);case"secret.cli.pi.config":return d($,s(process.env.PI_CODING_AGENT_DIR,"~/.pi/agent",Z,Q),["models.json"]);case"secret.cli.amp":{let K=L0("~",Z,Q);return[Y1(s(process.env.XDG_DATA_HOME,"~/.local/share",Z,Q),"amp"),Y1(K,".local","share","amp")].some((B)=>d($,B,["secrets.json"]))||E2($,Y1(K,".amp"),["oauth"])}case"secret.cli.amp.config":{let K=["settings.json","settings.jsonc"],Y=[Y1(s(process.env.XDG_CONFIG_HOME,"~/.config",Z,Q),"amp"),Y1(L0("~",Z,Q),".config","amp")],B=e($).split("/");return Y.some((W)=>d($,W,K))||B.at(-2)===".amp"&&K.includes(B.at(-1)??"")||(process.env.AMP_SETTINGS_FILE?.trim()?T2($,process.env.AMP_SETTINGS_FILE,Z,Q):!1)}case"secret.cli.cursor":{let K=Y1(s(process.env.XDG_CONFIG_HOME,"~/.config",Z,Q),"cursor"),Y=Y1(s(process.env.CURSOR_DATA_DIR,"~/.cursor",Z,Q),"projects");return d($,L0("~/.cursor",Z,Q),["auth.json"])||d($,K,["auth.json"])||e($).split("/").at(-1)==="mcp-auth.json"&&A3(e($),e(Y))}case"secret.cli.cursor.config":{let K=e($).split("/");return K.at(-1)==="mcp.json"&&K.at(-2)===".cursor"}default:return!1}})?.id??null}function s($,Z,J,Q){return L0($?.trim()?$:Z,J,Q)}function d($,Z,J){return J.some((Q)=>oQ($,Y1(Z,Q)))}function E2($,Z,J){return J.some((Q)=>A3(e($),e(Y1(Z,Q))))}function T2($,Z,J,Q){return oQ($,L0(Z,J,Q))}function oQ($,Z){return e($)===e(Z)}function Y1($,...Z){return y$([$,...Z].filter(Boolean).join("/"))}function eO($,Z,J,Q,X){if(J.length===0)return!1;let K=e(uQ($,Z,X));return J.some((Y)=>A3(K,e(uQ(Y,Q,X))))}function $L($){let Z=$.split("/");return Z.some((J)=>nO.has(J))||aO.some(([J,Q])=>Z.some((X,K)=>X===J&&Z[K+1]===Q))}function ZL($,Z){let J=$.lastIndexOf("."),Q=J>0&&J<$.length-1?$.slice(J+1):"";if(Q==="")return null;for(let X of x9)if(Q===X.extension&&O0(X.id,Z))return X.id;for(let X of l9)if(X.pattern.test(Q)&&O0(X.id,Z))return X.id;return null}function e($){return $.toLowerCase()}function O0($,Z){if(!Z?.disabledRules)return!0;if(Array.isArray(Z.disabledRules))return!Z.disabledRules.includes($);return!Z.disabledRules.has($)}function L0($,Z,J){let{home:Q,normalized:X}=tQ($,J);if(!X)return"";if(!Q)return X;let K=eQ(X,Q),Y=s9(K)?K:y$(hQ(Z,K)),B=y$(i(Y,R0,J));if(!A3(B,Q)){if(s9(K))return B;return B===Y?X:B}let W=B.slice(Q.length);return W?`~${W}`:"~"}function uQ($,Z,J){let{home:Q,normalized:X}=tQ($,J);if(!X)return"";let K=Q?eQ(X,Q):X;return y$(i(s9(K)?K:hQ(Z,K),R0,J))}function tQ($,Z){let J=process.env.HOME??n_(),Q=J?y$(i(J,R0,Z)):"",X=y$(JL(d1($)));return{home:Q,normalized:X}}function JL($){if(!$.trim().toLowerCase().startsWith("file:"))return $;try{return a_($)}catch{return $}}function eQ($,Z){if($==="~")return Z;if($.startsWith("~/"))return Y1(Z,$.slice(2));return $}function y$($){let Z=$.trim().replace(/\\/g,"/").replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(Z==="/")return Z;return Z.replace(/\/+$/g,"")}function A3($,Z){return $===Z||$.startsWith(Z.endsWith("/")?Z:`${Z}/`)}function o0($){return $.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??$}import{dirname as M0}from"node:path";var $X="Rulebook exceeds CC Safety Net's safe validation limits.",ZX="Additional rulebook validation errors were omitted.",l1=Object.freeze({maxAllowedCommands:1024,maxRules:1024,maxTests:2048,maxBlockArgsPerRule:1024,maxTotalBlockArgs:16384,maxStringCodeUnits:1048576,maxAggregateStringCodeUnits:4194304,maxFixtureCommandCodeUnits:131072,maxValidationErrors:64});function JX($){if(r9($.allowed_commands,l1.maxAllowedCommands)||r9($.rules,l1.maxRules)||r9($.tests,l1.maxTests))return!1;let{maxAggregateStringCodeUnits:Z,maxTotalBlockArgs:J}=l1,Q=(X,K=!1)=>{if(typeof X!=="string")return!0;if(X.length>l1.maxStringCodeUnits||K&&X.length>l1.maxFixtureCommandCodeUnits||X.length>Z)return!1;return Z-=X.length,!0};if(!Q($.name)||!Q($.version)||!Q($.description)||!Q($.author)||!Q($.migrated_from))return!1;if(Array.isArray($.allowed_commands)){for(let X of $.allowed_commands)if(!Q(X))return!1}if(Array.isArray($.rules))for(let X of $.rules){if(!X||typeof X!=="object")continue;let K=X;if(!Q(K.name)||!Q(K.command)||!Q(K.subcommand)||!Q(K.reason)||!Q(K.intent))return!1;if(!Array.isArray(K.block_args))continue;if(K.block_args.length>l1.maxBlockArgsPerRule||K.block_args.length>J)return!1;J-=K.block_args.length;for(let Y of K.block_args)if(!Q(Y))return!1}if(Array.isArray($.tests))for(let X of $.tests){if(!X||typeof X!=="object")continue;let K=X;if(!Q(K.command,!0)||!Q(K.expect)||!Q(K.rule))return!1}return!0}function r9($,Z){return Array.isArray($)&&$.length>Z}function QL($){if(!XL($))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!JX($))return{errors:[$X],ruleNames:new Set};let Z=UQ().safeParse($),J=[...$.rulebook_version===1?[]:["rulebook_version must be 1"],...Z.success?[]:P$(Z.error.issues,": ",": ")];return{errors:J.length>l1.maxValidationErrors?[...J.slice(0,l1.maxValidationErrors),ZX]:J,ruleNames:new Set(m9($).map((Q)=>Q.toLowerCase()))}}function v$($){let Z=QL($);if(Z.errors.length>0)throw Error(Z.errors.join("; "));return $}function XL($){return!!$&&typeof $==="object"&&!Array.isArray($)}var KL=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#([A-Za-z0-9._-]+)$/;function E3($){if(J$($.spec))return BL($);return YL($)}function YL($){if(!z1.test($.spec))return`Local rulebook sources must be bare names matching ${z1}: ${$.spec}`;if($.kind!=="local-directory")return`lock entry for ${$.spec} must use local-directory kind`;if($.path===$.spec&&$.name===$.spec)return null;return`lock entry for ${$.spec} does not match local source identity`}function BL($){let Z=m$($.spec);if(Z)return Z;let J=Z$($.spec);if($.kind!=="github")return`lock entry for ${$.spec} must use github kind`;if($.owner===J.owner&&$.repo===J.repo&&$.ref===J.ref&&$.path===J.path&&$.name===J.name)return null;return`lock entry for ${$.spec} does not match GitHub source identity`}function ob($,Z,J){let Q=XX($.rules,J);if(Q.length>0)return{ok:!0,specs:Q};if(!Z)return{ok:!1,result:{ok:!1,errors:[`No lockfile available to match rulebook name ${J}; use the exact source or run ${S1}`],warnings:[],entries:[]}};let X=new Set($.rules),K=Z.rulebooks.filter((Y)=>Y.name===J&&X.has(Y.spec)).map((Y)=>Y.spec);if(K.length===1)return{ok:!0,specs:K};return QX(J,K)}function tb($,Z,J){let Q=XX($,J);if(Q.length>0)return{ok:!0,specs:Q};let X=WL($,J);if(X.length>0)return{ok:!0,specs:X};let K=qL($,J);if(!K.ok)return K;if(K.specs.length>0)return{ok:!0,specs:K.specs};let Y=Z?$.filter((B)=>Z.rulebooks.find((W)=>W.spec===B)?.name===J):[];if(Y.length===1)return{ok:!0,specs:Y};return QX(J,Y)}function QX($,Z){return{ok:!1,result:{ok:!1,errors:Z.length===0?[`No configured rulebook matches ${$}`]:[`Ambiguous rulebook match ${$}: ${Z.join(", ")}`],warnings:[],entries:[]}}}function XX($,Z){return $.filter((J)=>J===Z)}function WL($,Z){let J=Z.match(KL),Q=J?.[1],X=J?.[2],K=J?.[3];if(!Q||!X||!K)return[];return YX($,(Y)=>{return Y.owner===Q&&Y.repo===X&&Y.ref===K})}function qL($,Z){if(!NZ(Z))return{ok:!0,specs:[]};let[J,Q]=Z.split("/"),X=YX($,(Y)=>{return Y.owner===J&&Y.repo===Q});if(new Set(X.map((Y)=>KX(Y)?.ref).filter((Y)=>!!Y)).size<2)return{ok:!0,specs:X};return{ok:!1,result:{ok:!1,errors:[`Multiple refs are configured for ${Z}. Use an explicit ref:`,` cc-safety-net rule remove ${Z}#<ref>`],warnings:[],entries:[]}}}function KX($){try{return Z$($)}catch{return null}}function YX($,Z){return $.filter((J)=>{let Q=KX(J);return Q?Z(Q):!1})}function n9($){let Z=typeof $==="string"?$:$.path;try{let J=X0(typeof $==="string"?u2($):$);if(J===null)return{lock:null,errors:[]};let Q=JSON.parse(J);if(!Q||typeof Q!=="object")return{lock:null,errors:[`malformed lockfile ${Z}: must be an object`]};let X=Q;if(X.version!==1||!Array.isArray(X.rulebooks))return{lock:null,errors:[`malformed lockfile ${Z}`]};let K=GQ().safeParse(X),Y=X.rulebooks.flatMap((W,q)=>{let U=K.success?[]:K.error.issues.filter((j)=>j.path[1]===q);if(U.length>0)return P$(U).map((j)=>`${Z}: ${j}`);let H=E3(W);return H?[`${Z}: rulebooks[${q}]: ${H}`]:[]});if(!K.success||Y.length>0)return{lock:null,errors:[`malformed lockfile ${Z}`,...Y]};return{lock:{version:1,rulebooks:K.data.rulebooks.map((W)=>{if(W.kind==="local-directory")return{spec:W.spec,kind:W.kind,path:W.path,name:W.name,version:W.version,digest:W.digest};let q={spec:W.spec,kind:W.kind,owner:W.owner,repo:W.repo,ref:W.ref,commit:W.commit,path:W.path,name:W.name,version:W.version,digest:W.digest};return typeof W.display_ref==="string"&&W.display_ref!==""?{...q,display_ref:W.display_ref}:q})},errors:[]}}catch(J){if(J instanceof u)return{lock:null,errors:[J.message]};return{lock:null,errors:["malformed lockfile"]}}}import{createHash as UL}from"node:crypto";import{dirname as T3,join as GL}from"node:path";var qX=Object.freeze({timeoutMs:15000,metadataBytes:524288,commitBytes:262144,treeBytes:16777216,rawBytes:4194304});async function BX($,Z,J,Q=D1(T3(T3(Z)),"rules policy"),X=z3()){if(J$($))return jL($,X);return HL($,Z,J,Q)}async function HI($,Z,J,Q,X,K=z3()){if(!J$($)||J.refresh)return BX($,Z,J,X,K);let Y=Q?.rulebooks.find((B)=>B.spec===$);if(!Y||Y.kind!=="github")return BX($,Z,J,X,K);return _L(Y,Z,J,X,K)}async function jI($,Z=z3()){let[J,Q]=$.split("/");if(!J||!Q)throw Error(`Invalid GitHub repository source: ${$}`);let X=await y2(`https://api.github.com/repos/${J}/${Q}`,"metadata",Z),K=X.response;if(!K.ok)throw Error(`Failed to inspect ${$}: GitHub returned ${K.status}`);let Y=JSON.parse(X.content);if(!Y.default_branch)throw Error(`Failed to inspect ${$}: missing default branch`);let B=await GX(J,Q,Y.default_branch,$,Z),W=await y2(`https://api.github.com/repos/${J}/${Q}/git/trees/${B}?recursive=1`,"tree",Z),q=W.response;if(!q.ok)throw Error(`Failed to inspect ${$}: GitHub tree returned ${q.status}`);let H=(JSON.parse(W.content).tree??[]).flatMap((j)=>{if(j.type!=="blob"||typeof j.path!=="string")return[];let G=j.path.match(l3);return G?.[1]?[G[1]]:[]}).sort();if(H.length===0)throw Error(`No rulebooks found in ${$} under ${k2}/`);return H.map((j)=>({spec:`${J}/${Q}#${B}/${j}`,display_ref:Y.default_branch}))}function HL($,Z,J,Q){m3($);let X=FL(Z,$),K=X0(X1(Q,X));if(K===null)throw Error(`Rulebook source not found: ${$}`);let Y=v$(a9(K,"Invalid local rulebook source."));if(Y.name!==$)throw Error(`rulebook name "${Y.name}" must match local source "${$}"`);return{rulebook:Y,content:K,entry:{spec:$,kind:"local-directory",path:$,name:Y.name,version:Y.version,digest:u$(K)}}}async function jL($,Z){let J=Z$($),Q=await GX(J.owner,J.repo,J.ref,$,Z),X=await y2(`https://raw.githubusercontent.com/${J.owner}/${J.repo}/${Q}/${J.path}`,"raw",Z),K=X.response;if(!K.ok)throw Error(`Failed to fetch ${$}: GitHub raw returned ${K.status}`);let Y=X.content,B=v$(a9(Y,"Invalid GitHub rulebook response."));if(B.name!==J.name)throw Error(`rulebook name "${B.name}" must match GitHub source "${J.name}"`);return{rulebook:B,content:Y,entry:{spec:$,kind:"github",owner:J.owner,repo:J.repo,ref:J.ref,commit:Q,path:J.path,name:B.name,version:B.version,digest:u$(Y)}}}async function _L($,Z,J,Q=D1(T3(T3(Z)),"rules policy"),X){let K=E3($);if(K)throw Error(`${K}; run ${S1}`);let Y=l2($,m2(Z,J)),B=X0(X1(Q,Y));if(B!==null){if(u$(B)===$.digest)return{entry:$,rulebook:UX(B,$),content:B}}return OL($,X)}async function OL($,Z){let J=await y2(`https://raw.githubusercontent.com/${$.owner}/${$.repo}/${$.commit}/${$.path}`,"raw",Z),Q=J.response;if(!Q.ok)throw Error(`Failed to restore ${$.spec}: GitHub raw returned ${Q.status}`);let X=J.content;if(u$(X)!==$.digest)throw Error(`locked GitHub digest mismatch for ${$.spec}; run ${S1}`);return{entry:$,rulebook:UX(X,$),content:X}}function UX($,Z){let J=v$(a9($,"Invalid cached rulebook."));if(J.name!==Z.name)throw Error(`rulebook name "${J.name}" must match lock entry "${Z.name}"`);return J}function a9($,Z){try{return JSON.parse($)}catch{throw Error(Z)}}async function GX($,Z,J,Q,X){let K=await y2(`https://api.github.com/repos/${$}/${Z}/commits/${encodeURIComponent(J)}`,"commit",X),Y=K.response;if(!Y.ok)throw Error(`Failed to resolve ${Q}: GitHub returned ${Y.status}`);let B=JSON.parse(K.content);if(!B.sha)throw Error(`Failed to resolve commit for ${Q}`);return B.sha}async function LL($,Z,J={}){if(J.signal?.aborted)throw J.signal.reason;let Q=J.budget??D3(),X=new AbortController,K=()=>X.abort(J.signal?.reason);J.signal?.addEventListener("abort",K,{once:!0});let Y=!1,B=setTimeout(()=>{if(X.signal.aborted)return;Y=!0,X.abort()},J.timeoutMs??qX.timeoutMs);try{if(J.signal?.aborted)throw J.signal.reason;XQ(Q);let W=await(J.fetch??fetch)($,{signal:X.signal,redirect:"error"});if(!W.ok)return HX(W),{response:W,content:""};return{response:W,content:await ML(W,Z,Q,()=>X.abort())}}catch(W){if(Y)throw Error("GitHub request timed out",{cause:W});if(J.signal?.aborted)throw J.signal.reason;throw W}finally{clearTimeout(B),J.signal?.removeEventListener("abort",K)}}function y2($,Z,J){return LL(J.resolveUrl?.($)??$,Z,{budget:J.budget,signal:J.controller.signal})}async function ML($,Z,J=D3(),Q){let X=qX[`${Z}Bytes`],K=Number($.headers.get("content-length"));if(Number.isFinite(K)&&K>X)throw HX($),Error(`GitHub ${Z} response exceeds ${X} bytes`);if(!$.body)return"";let Y=$.body.getReader(),B=[],W=0;while(!0){let q=await Y.read();if(q.done)break;try{KQ(J,q.value.byteLength)}catch(U){throw Q?.(),WX(Y),U}if(W+=q.value.byteLength,W>X)throw Q?.(),WX(Y),Error(`GitHub ${Z} response exceeds ${X} bytes`);B.push(Buffer.from(q.value))}return Buffer.concat(B,W).toString("utf-8")}function HX($){if(!$.body)return;jX(()=>$.body?.cancel())}function WX($){jX(()=>$.cancel())}function jX($){try{Promise.resolve($()).catch(()=>{})}catch{}}function FL($,Z){return GL($,Z,g2)}function u$($){return`sha256:${UL("sha256").update($).digest("hex")}`}function LX($={}){let Z=fZ($),J=!1;try{J=HZ(Z.userConfigTarget,Z.projectConfigTarget)}catch(j){if(j instanceof u)return bL(Z,j.message);throw j}let Q=C$(Z.userConfigTarget),X=J?{config:null,errors:[]}:C$(Z.projectConfigTarget),K=OX(Z.userConfigPath,Q.errors),Y=OX(Z.projectConfigPath,X.errors),B=new Set,W=Q.config?o9(Q.config,Z.userLockPath,M0(Z.userConfigPath),$,"user",Z.userScope,B):w2(),q=X.config?o9(X.config,Z.projectLockPath,M0(Z.projectConfigPath),$,"project",Z.projectScope,B):w2(),U=Q.config?.overrides??{},H=X.config?.overrides??{};return{rules:[..._X(W.rules,U),..._X(q.rules,H)],transparent_wrappers:DL(Q.config,X.config),rulebooks:[...W.rulebooks,...q.rulebooks],errors:[...K,...Y,...W.errors,...q.errors],warnings:[...W.warnings,...q.warnings,...W.canValidateOverrides?t9(U,W.knownRuleIds,Z.userConfigPath):[],...W.canValidateOverrides?zL(H,W.knownRuleIds,Z.projectConfigPath):[],...q.canValidateOverrides?t9(H,q.knownRuleIds,Z.projectConfigPath):[]],userConfig:Q.config??void 0,projectConfig:X.config??void 0,...Z}}function DI($,Z){let J=Z??D1(M0(M0($)),"rules policy"),Q=C$(X1(J,$)).config,X=n9(X1(J,E0($))).lock;if(!Q||!X)return new Map;let K=new Set(Q.rules);return new Map(X.rulebooks.filter((Y)=>K.has(Y.spec)).map((Y)=>[Y.spec,AZ(Y)]))}function zI($,Z,J,Q){let X=NL($,Z,J,Q);if(!X)return[];return[...X.scope.errors,...X.scope.warnings,...VL(X.config,X.scope,$)]}function NL($,Z,J,Q){let X=Q??D1(M0(M0($)),"rules policy"),K=C$(X1(X,$)).config;if(!K)return null;return{config:K,scope:o9(K,Z,M0($),J,"project",X)}}function VL($,Z,J){return Z.canValidateOverrides?t9($.overrides??{},Z.knownRuleIds,J):[]}function o9($,Z,J,Q,X,K=D1(M0(M0(J)),X==="user"?"user policy":"project policy"),Y=new Set){let B;try{B=X1(K,Z)}catch(M){if(M instanceof u)return{...w2(),errors:[M.message],canValidateOverrides:!1};throw M}let W=n9(B);if(W.errors.length>0)return{...w2(),errors:W.errors,canValidateOverrides:!1};let q=W.lock;if(!q&&$.rules.length>0)return{...w2(),errors:[`missing lockfile ${Z}; run ${S1}`],canValidateOverrides:!1};let U=q?.rulebooks??[],H=new Map(U.map((M)=>[M.spec,M])),j=[],G=[],_=$.rules.flatMap((M)=>{let L=H.get(M);if(!L)return j.push(`missing lock entry for ${M}; run ${S1}`),[];let D=RL(L,J,Q,K);if(D.errors.length>0||!D.rulebook)return j.push(...D.errors),[];let z=D.rulebook;if(Y.has(z.name))return G.push(`duplicate active rulebook name "${z.name}" for ${M}; keeping the first and ignoring this one, so its rules are not active; rename one of them, then run ${S1}`),[];return Y.add(z.name),[{rules:z.rules.map((f)=>({...f,name:`${z.name}/${f.name}`})),rulebook:{source:X,spec:L.spec,name:z.name,version:z.version,rules:z.rules.map((f)=>`${z.name}/${f.name}`)}}]}),O=_.flatMap((M)=>M.rules);return{rules:O,rulebooks:_.map((M)=>M.rulebook),entries:U,knownRuleIds:new Set(O.map((M)=>M.name)),errors:j,warnings:G,canValidateOverrides:j.length===0}}function RL($,Z,J,Q){let X=l2($,m2(Z,J)),K;try{K=X0(X1(Q,X))}catch(B){if(B instanceof u)return{rulebook:null,errors:[B.message]};throw B}if(K===null)return{rulebook:null,errors:[`missing cache entry for ${$.spec}; run ${S1}`]};if(u$(K)!==$.digest)return{rulebook:null,errors:[`cache digest mismatch for ${$.spec}; run ${S1}`]};let Y;try{Y=JSON.parse(K)}catch{return{rulebook:null,errors:[`invalid cached rulebook for ${$.spec}`]}}try{v$(Y)}catch(B){return{rulebook:null,errors:[`invalid cached rulebook for ${$.spec}: ${B instanceof Error?B.message:"invalid rulebook"}`]}}return{rulebook:Y,errors:[]}}function DL($,Z){return[...new Set([...$?.transparent_wrappers??[],...Z?.transparent_wrappers??[]])]}function _X($,Z){return $.flatMap((J)=>{let Q=Z[J.name];if(Q==="off")return[];if(Q&&typeof Q==="object")return[{...J,intent:Q.intent??J.intent,reason:Q.reason}];return[J]})}function t9($,Z,J){return Object.keys($).filter((Q)=>!Z.has(Q)).map((Q)=>`unknown override key "${Q}" in ${J}; only that override is ignored and other overrides and rules keep their configured state; correct or remove it in that file`)}function zL($,Z,J){return Object.keys($).filter((Q)=>Z.has(Q)).map((Q)=>`project override cannot target user-scoped rule "${Q}" in ${J}; only that override is ignored and the rule keeps its user-configured state; remove it from that file`)}function OX($,Z){return Z.map((J)=>J.startsWith("Unable to access ")?J:`${$}: ${J}`)}function bL($,Z){return{rules:[],transparent_wrappers:[],rulebooks:[],errors:[Z],warnings:[],userConfigPath:$.userConfigPath,projectConfigPath:$.projectConfigPath,userLockPath:$.userLockPath,projectLockPath:$.projectLockPath}}function w2(){return{rules:[],rulebooks:[],entries:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}function MX($={}){let Z=LX($),J=VQ($),Q={rules:Z.rules,transparentWrappers:Z.transparent_wrappers,safety:EL(J.safety),worktreeMode:J.worktreeMode,destructiveCommandProtectionEnabled:J.destructiveCommandProtectionEnabled,destructiveCommandRuleOverrides:{...J.destructiveCommandRuleOverrides},destructiveCommandAllowPaths:[...J.destructiveCommandAllowPaths],secretProtection:{enabled:J.secretProtection.enabled??!0,disabledRules:[...J.secretProtection.disabledRules??[]],denyPaths:[...J.secretProtection.denyPaths]}},X={...Z.userConfig?.overrides??{},...Z.projectConfig?.overrides??{}},K=Object.freeze(Object.fromEntries(Q.rules.map((Y)=>{let B=Z.rulebooks.find((q)=>q.rules.includes(Y.name)),W=X[Y.name];return[Y.name,Object.freeze({id:Y.name,...B?{rulebook:Object.freeze({name:B.name,version:B.version}),...CL(B.spec)?{source:B.spec}:{}}:{},...W&&typeof W==="object"?{override:Object.freeze({type:"reason",reason:W.reason})}:{}})]})));return AL(Q,IL(Z,J),K)}function PI($){if($.state==="ready")return{state:$.state};return{state:$.state,reason:$.reason}}function IL($,Z){let J=PL(Z);if($.errors.length===0&&$.warnings.length===0&&!J)return;return{diagnostics:[...$.errors,...$.warnings,...Z.errors],reason:TL($.errors.length>0?fL($.errors):void 0,$.warnings.length>0?e9($.warnings.join("; ")):void 0,J)}}function fL($){return`${e9($.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function PL($){if($.errors.length===0)return;let Z=$.fallback==="salvaged"?"the salvaged policy with protective defaults":"built-in protective defaults";return`invalid policy config: ${$.errors.join("; ")}. Enforcing ${Z}; the invalid values are not active. Fix the policy file manually`}function CL($){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test($)}function AL($,Z,J=Object.freeze({})){let Q=FX(structuredClone($));if(!Z)return Object.freeze({state:"ready",policy:Q,diagnostics:Object.freeze([]),ruleMetadata:J});return Object.freeze({state:"degraded",policy:Q,diagnostics:Object.freeze([...Z.diagnostics]),reason:Z.reason,ruleMetadata:J})}function EL($){let Z=$.overrides,J={...Z?.failClosed!==void 0?{failClosed:Z.failClosed}:{},...Z?.paranoidRm!==void 0?{paranoidRm:Z.paranoidRm}:{},...Z?.paranoidInterpreters!==void 0?{paranoidInterpreters:Z.paranoidInterpreters}:{}};return{...$.level!==void 0?{level:$.level}:{},...Object.keys(J).length>0?{overrides:J}:{}}}function FX($){if(typeof $!=="object"||$===null)return $;for(let Z of Object.values($))FX(Z);return Object.freeze($)}function TL(...$){return e9($.filter((Z)=>!!Z).join("; "))}function e9($){return/[.!?]$/.test($)?$:`${$}.`}class h$ extends Error{stage;evaluation;name="GuardEvaluationError";constructor($,Z,J){super(`CC Safety Net ${$} dependency failed`,{cause:J});this.stage=$;this.evaluation=Z}}var SL={findPolicyMutation:PQ,findGitMetadataMutation:G7,resolveGitMetadata:S6,loadPolicySnapshot:MX,findSensitiveTarget:mQ,analyzeCommand:v9,getModes:c4};function NX($,Z={}){let J={...SL,...Z.dependencies},Q=vL($),X=v2($)?$.command:Q,K=t0("policy-protection",X,()=>F4($,Z.factParserDependencies)),Y=_1(K,"declared-command");if(v2($)&&$.command?.trim()&&Y?.program.status==="limited")return{stage:"command-analysis",decision:{kind:"deny",reason:Y0,intent:"stop_and_explain",evidence:[{kind:"command",command:$.command,segment:$.command}]}};if(_1(K,"input-candidate")?.program.status==="limited")return{stage:"command-validation",decision:{kind:"deny",reason:mZ,intent:"stop_and_explain",evidence:[]}};let B=t0("policy-protection",X,()=>J.resolveGitMetadata($.context.executionCwd)),W=t0("policy-protection",X,()=>J.findPolicyMutation(K));if(W){let M=X??W.target;return{stage:"policy-protection",decision:{kind:"deny",reason:fQ,intent:"hard_stop",evidence:[{kind:"command",command:M,segment:W.target},{kind:"path",target:W.target}]}}}let q=t0("policy-protection",X,()=>J.findGitMetadataMutation(K,B));if(q){let M=X??q.target;return{stage:"policy-protection",decision:{kind:"deny",reason:f1,intent:"hard_stop",evidence:[{kind:"command",command:M,segment:q.target},{kind:"path",target:q.target}]}}}let U=t0("config-load",X,()=>J.loadPolicySnapshot({...Z.policyOptions,cwd:$.context.configCwd})),H=U.policy,j=J.getModes(H),G={level:j.effectiveLevel,...yL(U)},_=H.secretProtection.enabled===!1?null:t0("secret-protection",X,()=>J.findSensitiveTarget(K,H.secretProtection,{strict:v2($)?j.strict:void 0}));if(_){let M=X??_.target;return{stage:"secret-protection",...G,decision:{kind:"deny",reason:gQ,intent:"hard_stop",ruleId:_.ruleId,evidence:[{kind:"command",command:M,segment:_.target},{kind:"path",target:_.target}]}}}if(!v2($))return{stage:"non-command",...G,decision:{kind:"allow"}};if(!$.command||$.command.trim()==="")return{...$Z("command-validation",X),...G};let O=t0("command-analysis",X,()=>{return J.analyzeCommand($.command,{cwd:$.context.executionCwd,shell:$.route.shell,policySnapshot:U,environment:B0(),protectedGitMetadata:B,effectiveCapabilities:j.capabilities,strict:j.strict,paranoidRm:j.paranoidRm,paranoidInterpreters:j.paranoidInterpreters,worktreeMode:j.worktreeMode},wL(K),K.store)});if(O)return{stage:"command-analysis",...G,decision:O};return{stage:"command-analysis",...G,decision:{kind:"allow"}}}function yL($){if($.state==="ready")return{};return{configFallback:{reason:$.reason}}}function wL($){return _1($,"declared-command")?.program}function vL($){try{return B$($.input)}catch(Z){let J=v2($)?$.command:void 0;throw new h$("policy-protection",$Z("policy-protection",Z instanceof W0?void 0:J),Z)}}function t0($,Z,J){try{return J()}catch(Q){throw new h$($,$Z($,Q instanceof W0?void 0:Z),Q)}}function $Z($,Z){return{stage:$,decision:{kind:"deny",reason:i2,intent:"stop_and_explain",evidence:Z?[{kind:"command",command:Z,segment:Z}]:[]}}}function v2($){return $.route.kind==="command"}import{realpathSync as uL,statSync as hL}from"node:fs";import{isAbsolute as VX,relative as gL,resolve as kL,sep as xL}from"node:path";function lL($,Z){if(v0($))return;let J=Z.flatMap((X)=>ZZ(X));if(!J[0])return;let Q=ZZ(VX($)?$:kL(J[0],$))[0];if(!Q)return;return J.some((X)=>RX(Q,X))?Q:void 0}function mL($){return $.flatMap((Z)=>ZZ(Z))[0]}function ZZ($){try{let Z=uL($);return hL(Z).isDirectory()?[Z]:[]}catch{return[]}}function RX($,Z){let J=gL(Z,$);return J===""||J!==".."&&!J.startsWith(`..${xL}`)&&!VX(J)}function nI($,Z){try{let J=NX($,Z.guard);return DX($,J,Z),J}catch(J){if(!(J instanceof h$))throw J;throw DX($,J.evaluation,Z,!(J.cause instanceof W0),{stage:J.stage,errorCode:pL(J.cause)}),J}}function DX($,Z,J,Q=!0,X){lZ(xZ($,Z,J.guard?.auditAllowed??!1,Q,X),J.audit.getSessionId,{agent:J.audit.agent,shape:J.audit.shape,homeDir:J.audit.homeDir})}function pL($){if($ instanceof y1)return"path-canonicalization-limit";if($ instanceof W0)return"tool-input-limit";if($ instanceof z0)return"structural-shell-syntax-limit";return"unexpected-error"}
64
64
  export{XZ as b,bX as c,cL as d,dL as e,iL as f,u as g,X1 as h,u2 as i,X0 as j,GZ as k,HZ as l,oL as m,tL as n,eL as o,$M as p,hX as q,z1 as r,g2 as s,k2 as t,NZ as u,S1 as v,bZ as w,IZ as x,WM as y,E0 as z,qM as A,UM as B,fZ as C,GM as D,AZ as E,l2 as F,HM as G,m2 as H,jK as I,uZ as J,gZ as K,EK as L,EM as M,hM as N,gM as O,kM as P,xM as Q,y1 as R,d$ as S,i as T,R0 as U,B0 as V,r2 as W,n3 as X,T0 as Y,W0 as Z,rK as _,B$ as $,e3 as aa,$6 as ba,F4 as ca,YB as da,f1 as ea,G7 as fa,S6 as ga,E7 as ha,NV as ia,o as ja,jq as ka,_q as la,c4 as ma,x0 as na,x6 as oa,DN as pa,T7 as qa,Cz as ra,v9 as sa,oJ as ta,P2 as ua,QQ as va,JQ as wa,z3 as xa,eJ as ya,dz as za,m9 as Aa,C2 as Ba,P$ as Ca,T_ as Da,C$ as Ea,oz as Fa,tz as Ga,ez as Ha,I3 as Ia,P3 as Ja,T$ as Ka,Hb as La,f3 as Ma,jb as Na,u_ as Oa,_b as Pa,E$ as Qa,RQ as Ra,DQ as Sa,fQ as Ta,PQ as Ua,gQ as Va,mQ as Wa,v$ as Xa,ob as Ya,tb as Za,n9 as _a,HI as $a,jI as ab,LX as bb,DI as cb,zI as db,o9 as eb,MX as fb,PI as gb,AL as hb,h$ as ib,lL as jb,mL as kb,RX as lb,nI as mb};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as B}from"./chunks/index-25nh5wqs.js";import{$ as O,M as F,N as W,O as H,P as L,Z as x,_ as M,ib as b,la as N,mb as k,ta as _}from"./chunks/index-3k09xczv.js";import{accessSync as m,constants as R,statSync as w}from"node:fs";import{resolve as S}from"node:path";var P="cc-safety-net";function X(q){let J=new Set(q??[]),K={},Q={description:"Manage CC Safety Net rulebooks",template:B.slice(B.indexOf("## Workflow"))};if(!J.has(P))K[P]=Q;return K}var C=new Set(["powershell","pwsh"]),s=new Set(["bash","dash","ksh","sh","zsh"]);function T(q={}){return async({directory:J,homeDir:K})=>{let Q=S(J),$;return{config:async(Z)=>{$=Z;let Y=X(),j=Z.command??{};Z.command={...Y,...j}},"tool.execute.before":async(Z,Y)=>{let j=(V,g,h=Q)=>{F(V,()=>Z.sessionID,{agent:"opencode",toolName:g,cwd:h,homeDir:K}),I(V)};if(typeof Z.tool!=="string"||Z.tool.trim()==="")j(H());let y=Y.args,z;try{z=O(y)}catch(V){if(!(V instanceof x))throw V;j(H({toolName:Z.tool}),Z.tool)}let D=p($?.shell),f=c(Z.tool,D),G=u(Q,y);if(!A(Q)||!G)return j(H({command:z,toolName:Z.tool}),Z.tool);let E={configCwd:Q,executionCwd:G},v=_(Z.tool,y,f,E,z??null);try{let V=k(v,{guard:{auditAllowed:N(),dependencies:q},audit:{agent:"opencode",homeDir:K,getSessionId:()=>Z.sessionID}});U(V,V.stage!=="config-state")}catch(V){if(!(V instanceof b))throw V;if(V.stage==="policy-protection"||V.stage==="config-load"||V.stage==="secret-protection")throw V.cause;U(V.evaluation,!0);return}}}}}function p(q){if(typeof q!=="string")return"auto";let J=q.trim().split(/[\\/]/).at(-1)?.toLowerCase().replace(/\.exe$/,"");if(!J)return"auto";if(C.has(J))return"powershell";if(s.has(J))return"posix";return"auto"}function c(q,J){if(q==="bash")return{kind:"command",shell:J};return{kind:M(q)}}function u(q,J){if(!J||typeof J!=="object"||Array.isArray(J))return q;if(!Object.hasOwn(J,"workdir"))return q;let K=J.workdir;if(typeof K!=="string"||K.trim()==="")return null;let Q=process.platform==="win32"?a(K):K;if(!Q)return null;let $=S(q,Q);return A($)?$:null}function a(q){let J=q.replace(/^\/([a-zA-Z]):(?:[\\/]|$)/,(K,Q)=>`${Q.toUpperCase()}:/`).replace(/^\/([a-zA-Z])(?:[\\/]|$)/,(K,Q)=>`${Q.toUpperCase()}:/`).replace(/^\/cygdrive\/([a-zA-Z])(?:[\\/]|$)/,(K,Q)=>`${Q.toUpperCase()}:/`).replace(/^\/mnt\/([a-zA-Z])(?:[\\/]|$)/,(K,Q)=>`${Q.toUpperCase()}:/`);return J.startsWith("/")?null:J}function A(q){try{if(!w(q).isDirectory())return!1;return m(q,R.R_OK|R.X_OK),!0}catch{return!1}}function U(q,J){let K=W(q,{includeEvidence:J});if(K)I(K)}function I(q){throw Error(L(q))}var Hq=T();export{Hq as CCSafetyNetPlugin};
1
+ import{a as B}from"./chunks/index-25nh5wqs.js";import{$ as O,M as F,N as W,O as H,P as L,Z as x,_ as M,ib as b,la as N,mb as k,ta as _}from"./chunks/index-bmvm3x9s.js";import{accessSync as m,constants as R,statSync as w}from"node:fs";import{resolve as S}from"node:path";var P="cc-safety-net";function X(q){let J=new Set(q??[]),K={},Q={description:"Manage CC Safety Net rulebooks",template:B.slice(B.indexOf("## Workflow"))};if(!J.has(P))K[P]=Q;return K}var C=new Set(["powershell","pwsh"]),s=new Set(["bash","dash","ksh","sh","zsh"]);function T(q={}){return async({directory:J,homeDir:K})=>{let Q=S(J),$;return{config:async(Z)=>{$=Z;let Y=X(),j=Z.command??{};Z.command={...Y,...j}},"tool.execute.before":async(Z,Y)=>{let j=(V,g,h=Q)=>{F(V,()=>Z.sessionID,{agent:"opencode",toolName:g,cwd:h,homeDir:K}),I(V)};if(typeof Z.tool!=="string"||Z.tool.trim()==="")j(H());let y=Y.args,z;try{z=O(y)}catch(V){if(!(V instanceof x))throw V;j(H({toolName:Z.tool}),Z.tool)}let D=p($?.shell),f=c(Z.tool,D),G=u(Q,y);if(!A(Q)||!G)return j(H({command:z,toolName:Z.tool}),Z.tool);let E={configCwd:Q,executionCwd:G},v=_(Z.tool,y,f,E,z??null);try{let V=k(v,{guard:{auditAllowed:N(),dependencies:q},audit:{agent:"opencode",homeDir:K,getSessionId:()=>Z.sessionID}});U(V,V.stage!=="config-state")}catch(V){if(!(V instanceof b))throw V;if(V.stage==="policy-protection"||V.stage==="config-load"||V.stage==="secret-protection")throw V.cause;U(V.evaluation,!0);return}}}}}function p(q){if(typeof q!=="string")return"auto";let J=q.trim().split(/[\\/]/).at(-1)?.toLowerCase().replace(/\.exe$/,"");if(!J)return"auto";if(C.has(J))return"powershell";if(s.has(J))return"posix";return"auto"}function c(q,J){if(q==="bash")return{kind:"command",shell:J};return{kind:M(q)}}function u(q,J){if(!J||typeof J!=="object"||Array.isArray(J))return q;if(!Object.hasOwn(J,"workdir"))return q;let K=J.workdir;if(typeof K!=="string"||K.trim()==="")return null;let Q=process.platform==="win32"?a(K):K;if(!Q)return null;let $=S(q,Q);return A($)?$:null}function a(q){let J=q.replace(/^\/([a-zA-Z]):(?:[\\/]|$)/,(K,Q)=>`${Q.toUpperCase()}:/`).replace(/^\/([a-zA-Z])(?:[\\/]|$)/,(K,Q)=>`${Q.toUpperCase()}:/`).replace(/^\/cygdrive\/([a-zA-Z])(?:[\\/]|$)/,(K,Q)=>`${Q.toUpperCase()}:/`).replace(/^\/mnt\/([a-zA-Z])(?:[\\/]|$)/,(K,Q)=>`${Q.toUpperCase()}:/`);return J.startsWith("/")?null:J}function A(q){try{if(!w(q).isDirectory())return!1;return m(q,R.R_OK|R.X_OK),!0}catch{return!1}}function U(q,J){let K=W(q,{includeEvidence:J});if(K)I(K)}function I(q){throw Error(L(q))}var Hq=T();export{Hq as CCSafetyNetPlugin};