cc-safety-net 2.7.4 → 2.7.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,11 +1,11 @@
1
1
  // cc-safety-net managed Amp plugin. Do not edit. Reinstall with: npx -y cc-safety-net install --amp
2
- // version: 2.7.4
2
+ // version: 2.7.5
3
3
  // @bun
4
4
  var cs="CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry.",et="Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry.",cr="CC Safety Net failed closed because command analysis failed unexpectedly. This is not caused by your command. Report it to the user.";var ls={errorCode:"path-canonicalization-limit",reason:"CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry."},En={errorCode:"structural-shell-syntax-limit",reason:"Command analysis exceeds CC Safety Net's derived-command work limit. Reduce nested or embedded command complexity and retry."},K=Object.freeze({realpathAttempts:{cap:16384,...ls},processedCandidateBytes:{cap:4194304,...ls},pathEnvironmentExpansion:{cap:64,...ls},recursionDepth:{cap:10,errorCode:"structural-shell-syntax-limit",reason:"Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry."},derivedTokens:{cap:16384,...En},trackedHeredocFiles:{cap:64,...En},scriptFiles:{cap:64,...En},controlFlowStates:{cap:64,...En},wrapperPeelIterations:{cap:20,...En},derivedCommandShape:En});class z extends Error{kind;name="AnalysisLimit";constructor(e){super(K[e].reason);this.kind=e}}function Re(){let e=new Map;return{counters:e,resolvedPaths:new Map,charge(t,n=1){let r=(e.get(t)??0)+n;if(e.set(t,r),r>K[t].cap)throw new z(t)}}}var kh=[/\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 wt(e){return Oh(e.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>"))}function Oh(e){return kh.reduce((t,n)=>t.replace(n,"<redacted>"),e.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>")).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>")}var Dh={hard_stop:"Do not retry this operation or attempt any workaround (other tools, flags, or paths). Report the block to the user and continue with the rest of the task.",use_alternative:"Do not retry the blocked form. Continue the task using the safer alternative described above.",scope_down:"Retry with a narrower, explicit target as described above. Escalate to the user if the broad operation is truly required.",manual_only:"If this operation is truly needed, ask the user for explicit permission and have them run the command manually.",stop_and_explain:"Do not brute-force variants. Simplify or restructure the command so it can be analyzed, or report the block to the user."};function Mh(e){let t=e.maxLen??200,n=e.redact??((o)=>o),r=(o)=>o.length>t?`${o.slice(0,t)}...`:o;return[e.askUser?"CC Safety Net could not verify this command":"BLOCKED by CC Safety Net",`Reason: ${n(e.reason)}`,e.ruleId?`Rule: ${e.ruleId}`:void 0,e.toolName?`Tool: ${e.toolName}`:void 0,e.command?`Command: ${r(n(e.command))}`:void 0,e.segment&&e.segment!==e.command?`Segment: ${r(n(e.segment))}`:void 0,e.cwd?`Working directory: ${r(n(e.cwd))}`:void 0,e.configWarning?`Config warning: ${n(e.configWarning)}`:void 0,e.askUser?"Approve only if you expected this command.":Dh[e.intent??"manual_only"]].filter((o)=>o!==void 0).join(`
5
5
 
6
6
  `)}function hc(e,t){if(e.decision.kind!=="deny")return;let n=t.includeEvidence?e.decision.evidence:void 0;return{reason:e.decision.reason,ruleId:e.decision.ruleId,intent:e.decision.intent,command:n?.command,segment:n?.segment,toolName:t.toolName,...e.configFallback?{configWarning:e.configFallback.reason}:{},...e.decision.unverifiedByStandardMode?{unverifiedByStandardMode:!0}:{}}}function dr(e={}){return{reason:cr,ruleId:"analysis.failed-closed",intent:"stop_and_explain",command:e.command,segment:e.segment??e.command,toolName:e.toolName}}function ur(e={}){return{reason:"CC Safety Net could not check this tool call because it arrived without a usable tool name or arguments. This is not a CC Safety Net failure. Send the call again with its tool name and complete arguments.",ruleId:"tool-call.malformed",intent:"use_alternative",command:e.command,segment:e.command,toolName:e.toolName}}var Nh={session:{unusable:{reason:"CC Safety Net cannot check tool calls because the session's working directory or workspace root no longer exists, is inaccessible, is not a directory, or uses an unsupported path form. Ask the user to restart the session from an existing directory.",intent:"hard_stop",ruleId:"cwd.session-unusable"},"outside-workspace":{reason:"CC Safety Net cannot check tool calls because the session's working directory is outside its workspace roots. Ask the user to restart the session from a directory inside the workspace.",intent:"hard_stop",ruleId:"cwd.session-outside-workspace"}},requested:{unusable:{reason:"CC Safety Net could not use the requested working directory because it does not exist, is inaccessible, is not a directory, or uses an unsupported path form. Use an existing accessible working directory. If the requested directory is missing, create it from an accessible location before retrying the command.",intent:"use_alternative",ruleId:"cwd.requested-unusable"},"outside-workspace":{reason:"CC Safety Net could not use the requested working directory because it is outside the session's workspace. Use a working directory inside the workspace.",intent:"use_alternative",ruleId:"cwd.requested-outside-workspace"}}};function mr(e,t={}){return{...Nh[e.directory][e.problem],command:t.command,toolName:t.toolName,cwd:e.cwd}}function yc(e){return Mh({...e,redact:wt})}function Sc(e){return wt(e instanceof Error?e.message:String(e))}import{types as Lh}from"util";var Wh=new Set(["applypatch","patch"]),Fh=new Set(["create","edit","listdir","listpermissions","ls","multiedit","multireplacefilecontent","notebookedit","read","readfile","readurlcontent","replacefilecontent","searchweb","strreplaceeditor","view","viewfile","write","writefile","writetofile"]),Gh=new Set(["grep","grepsearch","rg"]),zh=new Set(["find","findbyname","glob"]),$h=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),Bh=new Set(["command","diff","input","patch","patchtext"]),Cc=new TextEncoder,Uh=new TextDecoder,Hh=/\s/,jh=64;class lt extends Error{name="ToolInputLimitError";constructor(){super("tool input traversal limit exceeded")}}var fr=Object.freeze({maxDepth:64,maxNodes:1e4,maxKeys:1e4,maxStringBytes:1048576,maxAggregateStringBytes:4194304});function wc(e){return e.replace(/[-_\s]/g,"").toLowerCase()}function mo(e){return $h.has(wc(e))}function fs(e){let t=wc(e);if(Wh.has(t))return"patch";if(Gh.has(t))return"grep";if(zh.has(t))return"glob";if(Fh.has(t))return"path";return"unknown"}function gr(e){if(!e||typeof e!=="object")return;kc(e);let t=Object.getOwnPropertyDescriptor(e,"command");if(!t){if("command"in e)tt();return}if(t.get||t.set)tt();let n=t.value;return typeof n==="string"&&n!==""?n:void 0}function _c(e,t){return xc(e,t,!1,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function xc(e,t,n,r,o){let i=Ic(e,r,o);if(typeof e==="string")return n?[e]:[];if(!i)return[];let s=i.entries.flatMap(([a,l])=>xc(l,t,i.array?n:t.has(Ac(a)),r,o+1));return r.ancestors.delete(i.object),s}function Ac(e){return e.replace(/-/g,"_").toLowerCase()}function Pc(e){return Tc(e,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(qh)}function Tc(e,t,n,r){let o=Ic(e,n,r);if(typeof e==="string")return t?[e]:[];if(!o)return[];let i=o.entries.flatMap(([s,a])=>Tc(a,o.array?t:Bh.has(Ac(s)),n,r+1));return n.ancestors.delete(o.object),i}function Vh(e,t,n){if(t.nodes++,e!==null&&typeof e==="object"&&n>fr.maxDepth||t.nodes>fr.maxNodes)tt();if(typeof e!=="string")return;let r=Buffer.byteLength(e);if(t.stringBytes+=r,r>fr.maxStringBytes||t.stringBytes>fr.maxAggregateStringBytes)tt()}function Ic(e,t,n){if(Vh(e,t,n),!e||typeof e!=="object")return null;let r=kc(e);if(t.ancestors.has(e))tt();let o=Reflect.ownKeys(e);if(t.keys+=o.length,t.keys>fr.maxKeys)tt();let i=o.flatMap((s)=>{let a=Object.getOwnPropertyDescriptor(e,s);if(!a||a.get||a.set)tt();return typeof s==="string"&&a.enumerable?[[s,a.value]]:[]});return t.ancestors.add(e),{object:e,array:r,entries:i}}function kc(e){if(Lh.isProxy(e))tt();let t=Array.isArray(e),n=Object.getPrototypeOf(e);if(t&&n!==Array.prototype||!t&&n!==Object.prototype&&n!==null)tt();return t}function tt(){throw new lt}function qh(e){let t=[],n=e.split(/\r?\n/),r=!1,o=!1,i=null,s=null,a=()=>{o=!1,i=null,s=null};for(let l=0;l<n.length;l++){let c=n[l]??"";if(c==="*** Begin Patch"){r=!0,a();continue}if(c==="*** End Patch"){r=!1,a();continue}if(c.startsWith("@@")){let d=Kh(c);if(o=!0,i=d?.oldLines??null,s=d?.newLines??null,i===0&&s===0)a();continue}if(o&&i!==null&&s!==null){let d=c.startsWith(" ")||c.startsWith("-")?1:0,u=c.startsWith(" ")||c.startsWith("+")?1:0;if(i=Math.max(0,i-d),s=Math.max(0,s-u),i===0&&s===0)a();continue}if(c.startsWith("*** ")){a(),t.push(...ds(c));continue}if(o)continue;if(c.startsWith("diff --git ")){t.push(...ds(c));continue}if(c.startsWith("--- ")){let d=n[l+1]??"";if(!d.startsWith("+++ "))continue;t.push(...ms(uo(c.slice(4),!0),uo(d.slice(4),!0))),l++;continue}if(!r)t.push(...ds(c))}return t}function Kh(e){let t=/^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(e);if(!t)return null;return{oldLines:Number(t[1]??1),newLines:Number(t[2]??1)}}function ds(e){let t=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(e);if(t?.[1])return Rc(t[1]);let n=/^\*\*\* Move to: (.+)$/.exec(e);if(n?.[1])return Rc(n[1]);if(e.startsWith("diff --git "))return Yh(e.slice(11));let r=/^--- (.+)$/.exec(e);if(r?.[1])return Ec(r[1]);let o=/^\+\+\+ (.+)$/.exec(e);if(o?.[1])return Ec(o[1]);let i=/^(?:rename|copy) (?:from|to) (.+)$/.exec(e);if(i?.[1])return ny(i[1]);return[]}function Yh(e){let t=Zh(e);if(t.length===2&&t[0]&&t[1])return ms(t[0],t[1]);let n=Xh(e);return n?ms(e.slice(n.oldStart,n.oldEnd),e.slice(n.newStart,n.newEnd)):[]}function Zh(e){let t=[],n=0;while(n<e.length&&t.length<2){while($t(e[n]))n++;if(n>=e.length)break;let r=e[n]==='"'||e[n]==="'"?e[n]:void 0;if(!r){let i=n;while(n<e.length&&!$t(e[n]))n++;t.push(e.slice(i,n));continue}let o=Oc(e,n,r);if(!o)return[];t.push(o.value),n=o.end}while($t(e[n]))n++;return n===e.length?t:[]}function Xh(e){let t=0;while(t<e.length&&$t(e[t]))t++;let n=e.length;while(n>t&&$t(e[n-1]))n--;let r=0,o=t;while(o<n){if(!$t(e[o])){o++;continue}let i=o;while(o<n&&$t(e[o]))o++;if(i===t||o===n)continue;if(r++,r>jh)tt();if(Qh(e,t,i,o,n))return{oldStart:t,oldEnd:i,newStart:o,newEnd:n}}return null}function Qh(e,t,n,r,o){if(us(e,t,n,r,o))return!0;let i=bc(e,"/",t,n),s=bc(e,"/",r,o);if(i<=t||s<=r)return!1;if(us(e,t,i,r,s))return!1;return us(e,i+1,n,s+1,o)}function us(e,t,n,r,o){if(n-t!==o-r)return!1;for(let i=0;i<n-t;i++)if(e[t+i]!==e[r+i])return!1;return!0}function bc(e,t,n,r){for(let o=n;o<r;o++)if(e[o]===t)return o;return-1}function $t(e){return e!==void 0&&Hh.test(e)}function Oc(e,t,n){let r=[],o=t+1;while(o<e.length){let i=String.fromCodePoint(e.codePointAt(o)??0);if(i===n)return{value:Uh.decode(Uint8Array.from(r)),end:o+1};if(i!=="\\"||n==="'"){r.push(...Cc.encode(i)),o+=i.length;continue}let s=e.slice(o+1),a=/^[0-7]{1,3}/.exec(s)?.[0];if(a){r.push(Number.parseInt(a,8)),o+=a.length+1;continue}r.push(...Cc.encode(Jh(s[0]??""))),o+=2}return null}function Jh(e){return{a:"\x07",b:"\b",f:"\f",n:`
7
7
  `,r:"\r",t:"\t",v:"\v"}[e]??e}function ey(e){return pr(ry(e))}function ms(e,t){if(e==="/dev/null")return vc(t);if(t==="/dev/null")return vc(e);if(e.startsWith("a/")&&t.startsWith("b/"))return[e.slice(2),t.slice(2)].flatMap(pr);let n=ty(e,t)??(e===t?Dc(e):null);return[e,t,...n?[n]:[]].flatMap(pr)}function vc(e){let t=Dc(e);return[e,...t?[t]:[]].flatMap(pr)}function Dc(e){let t=e.indexOf("/");return t>0&&t<e.length-1?e.slice(t+1):null}function ty(e,t){let n=e.indexOf("/"),r=t.indexOf("/");if(n<1||r<1)return null;if(e.slice(0,n)===t.slice(0,r))return null;let o=e.slice(n+1);return o===t.slice(r+1)?o:null}function Ec(e){return ey(uo(e,!0))}function ny(e){return pr(uo(e,!1))}function uo(e,t){let n=e.trim(),r=n[0]==='"'||n[0]==="'"?n[0]:void 0;if(r){let o=Oc(n,0,r);if(o&&(t||n.slice(o.end).trim()===""))return o.value}return t?n.split("\t",1)[0]?.trim()??"":n}function ry(e){return e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function pr(e){return e===""||e==="/dev/null"?[]:[e]}function Rc(e){let t=e.split("\t",1)[0]?.trim().replace(/^['"]|['"]$/g,"")??"";return t===""||t==="/dev/null"?[]:[t]}import{isAbsolute as Cs,relative as my,resolve as zc,sep as fy}from"path";import{basename as Lc,dirname as oy,isAbsolute as iy,join as sy,normalize as ay,resolve as Mc}from"path";var ly=256,fo=new Set(["CC_SAFETY_NET_HOME","CLAUDE_CONFIG_DIR","CODEX_HOME","COPILOT_HOME","GEMINI_CLI_HOME","GROK_HOME","HOME","KIMI_CODE_HOME","KIMI_SHARE_DIR","OPENCODE_CONFIG","OPENCODE_CONFIG_DIR","PI_CODING_AGENT_DIR","ProgramData","TMPDIR","XDG_CONFIG_HOME","XDG_DATA_HOME"]);function pe(e,t=process.platform){if(t!=="win32")return e;return e.replace(/^\/([A-Za-z])(?:\/|$)/,"$1:/")}function ct(e,t=process.platform){if(t!=="win32")return!1;return(e[0]==="/"||e[0]==="\\")&&(e[1]==="/"||e[1]==="\\")}function ys(e,t){return ps(e,0,t)}function ps(e,t,n){let r="",o=0,i=0;while(o<e.length){if(e[o]!=="$"){r+=e[o],o++;continue}if(e[o+1]==="{"){let a=gs(e,o+2),l=cy(e,o,t);if(l===null){if(fo.has(a))throw new z("pathEnvironmentExpansion");if(i++,i>K.pathEnvironmentExpansion.cap)throw new z("pathEnvironmentExpansion");r+="${",o+=2;continue}let c=e.slice(o,l+1);r+=dy(c,t,n),o=l+1;continue}let s=gs(e,o+1);if(!s){r+="$",o++;continue}r+=hs(s,n)??`$${s}`,o+=s.length+1}return r}function cy(e,t,n){let r=1;for(let o=t+2;o<e.length;o++){if(e[o]==="\\"){o++;continue}if(e[o]==="$"&&e[o+1]==="{"){if(r++,n+r>K.pathEnvironmentExpansion.cap)throw new z("pathEnvironmentExpansion");o++;continue}if(e[o]!=="}")continue;if(r--,r===0)return o}return null}function dy(e,t,n){let r=e.slice(2,-1),o=gs(r,0);if(!o)return e;let i=r.slice(o.length);if(!i)return hs(o,n)??e;let s=[":-",":+",":=",":?","-","+","=","?"].find((c)=>i.startsWith(c));if(!s){if(fo.has(o))throw new z("pathEnvironmentExpansion");return e}if(!fo.has(o))return e;if(s.endsWith("="))throw new z("pathEnvironmentExpansion");let a=hs(o,n),l=s.startsWith(":")?a!==null&&a!=="":a!==null;if(s.endsWith("?")&&!l)throw new z("pathEnvironmentExpansion");if(s.endsWith("-")||s.endsWith("?"))return l?a??"":ps(i.slice(s.length),t+1,n);return l?ps(i.slice(s.length),t+1,n):""}function gs(e,t){if(!/[A-Za-z_]/.test(e[t]??""))return"";let n=t+1;while(/[A-Za-z0-9_]/.test(e[n]??""))n++;return e.slice(t,n)}function hs(e,t){if(!fo.has(e))return null;if(e==="HOME")return t.env.get("HOME")??t.home;return t.env.get(e)??null}function F(e,t,n){if(!e)return e;let r=n.resolvedPaths.get(e);if(r!==void 0)return r;let o=[],i=e;while(!0){Wc(n,i);let s=t.realpath(i);if(s!==null)return Nc(n,e,s,o);let a=oy(i);if(a===i||o.length>=ly)return Nc(n,e,i,o);o.push(Lc(i)),i=a}}function Nc(e,t,n,r){let o=r.length===0?n:sy(n,...r.reverse());return e.resolvedPaths.set(t,o),o}function uy(e,t,n){let r=n.resolvedPaths.get(e);if(r!==void 0)return r;Wc(n,e);let o=t.realpath(e);if(o!==null)n.resolvedPaths.set(e,o);return o}function Wc(e,t){e.charge("realpathAttempts"),e.charge("processedCandidateBytes",Buffer.byteLength(t))}function ge(e,t,n,r){let o=Gc(e,t,n);if(!o)return"";return F(o,n.paths,r).replace(/\\/g,"/")}function Fc(e,t,n,r,o){let i=Gc(e,t,n);if(!i)return null;if(o(Lc(i)))return F(i,n.paths,r).replace(/\\/g,"/");let s=uy(i,n.paths,r);return s===null?null:s.replace(/\\/g,"/")}function Gc(e,t,n){let r=n.home,o=ys(e.trim(),n).replace(/\\/g,"/");if(!o)return"";let i=o==="~"?r:o.startsWith("~/")?Mc(r,o.slice(2)):o,s=pe(i);return ay(iy(s)?s:Mc(t,s))}function $c(e,t,n){if(ct(e))return;let r=t.flatMap((i)=>Ss(i,n));if(!r[0])return;let o=Ss(Cs(e)?e:zc(r[0],e),n)[0];if(!o)return;return r.some((i)=>py(o,i))?o:void 0}function po(e,t,n){if(ct(e))return;return Ss(Cs(e)?e:zc(t,e),n)[0]}function Ss(e,t){let n=t.realpath(e);if(n===null)return[];return t.isDirectory(n)?[n]:[]}function py(e,t){let n=my(t,e);return n===""||n!==".."&&!n.startsWith(`..${fy}`)&&!Cs(n)}function hr(e,t,n,r,o){if(n.kind!=="command")return{toolName:e,input:t,route:n,context:r};return{toolName:e,input:t,route:n,context:r,command:o}}import{spawnSync as $y}from"child_process";import{lstatSync as By,realpathSync as Uy,statSync as Hy}from"fs";import{isAbsolute as jy}from"path";import{homedir as Vy,tmpdir as qy}from"os";import{statSync as Fy}from"fs";import{join as Gy}from"path";import{spawnSync as gy}from"child_process";import{accessSync as Bc,constants as Uc,existsSync as yr,lstatSync as hy,opendirSync as yy,readFileSync as Sr,realpathSync as Rn,statSync as wn}from"fs";import{dirname as Vc,isAbsolute as bs,join as We,resolve as go}from"path";var Sy=["/usr/bin/git","/usr/local/bin/git","/opt/homebrew/bin/git","C:\\Program Files\\Git\\cmd\\git.exe","C:\\Program Files\\Git\\bin\\git.exe"],Cy=5000;function qc(e,t=My(),n=Cy){let r=by(e),o=r===null?null:vy(r);if(r===null||o===null)return null;let i=Oy(r,o,t,n);return i===null?null:{recursiveSubmodules:i}}function by(e){try{let t=Rn(go(e));return wn(t).isDirectory()?t:null}catch{return null}}function vy(e){let t=ky(e);if(!t)return null;try{let n=hy(t);if(n.isSymbolicLink()||!n.isFile())return null;let r=vs(t);if(!r?.commonDir)return null;if(!wy(r.gitDir,t))return null;return Zc(r.gitDir,r.commonDir)?null:{gitDir:r.gitDir,commonDir:r.commonDir}}catch{return null}}function vs(e){try{let t=Ey(e);if(!t)return null;let n=Rn(bs(t)?t:go(Vc(e),t));if(!wn(n).isDirectory())return null;return{gitDir:n,commonDir:Ry(n)}}catch{return null}}function Ey(e){let t=Sr(e,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(!t.startsWith("gitdir:"))return null;return t.slice(7).trim()||null}function Ry(e){try{let t=Sr(We(e,"commondir"),"utf-8").split(/\r?\n/,1)[0]?.trim();if(!t)return null;let n=Rn(bs(t)?t:go(e,t));return wn(n).isDirectory()?n:null}catch{return null}}function wy(e,t){let n=_y(e);return n===null?!1:xy(e,n,t)}function _y(e){let t=We(e,"gitdir");if(!yr(t))return null;let n=Sr(t,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";return n===""?null:n}function xy(e,t,n){try{return Ay(bs(t)?t:go(e,t),n)}catch{return!1}}function Ay(e,t){try{let n=wn(e),r=wn(t);if(n.ino!==0&&r.ino!==0&&n.dev===r.dev&&n.ino===r.ino)return!0}catch{}return Hc(Rn.native(e))===Hc(Rn.native(t))}function Hc(e){let t=e.replace(/^\\\\\?\\UNC\\/i,"//").replace(/^\\\\\?\\/i,"").replace(/\\/g,"/"),n=t.length>1&&t.endsWith("/")?t.slice(0,-1):t;return process.platform==="win32"?n.toLowerCase():n}function Kc(e){try{return Bc(We(e,"objects"),Uc.X_OK),Bc(We(e,"refs"),Uc.X_OK),/^(?:ref:[\t\n\r ]*refs\/|[0-9a-fA-F]{40})/.test(Xc(We(e,"HEAD")))}catch{return!1}}function Yc(e){return yr(We(e,"commondir"))||Zc(e,e)}function Zc(e,t){return[We(t,"config"),We(e,"config.worktree")].some(Py)||Iy(e)}var jc=1048576;function Xc(e){let t=wn(e);if(!t.isFile()||t.size>jc)throw Error(`${e} is not a regular file within ${jc} bytes`);return Sr(e,"utf-8")}function Py(e){try{return/(?:^|[\s\]])worktree\s*=/i.test(Xc(e))}catch(t){return t.code!=="ENOENT"}}var Ty=1e4;function Iy(e){let t=[e],n=0;try{while(t.length>0){let r=t.pop(),o=yy(r);try{for(let i=o.readSync();i!==null;i=o.readSync()){if(n++,i.isSymbolicLink()||i.isFIFO()||n>Ty)return!0;let s=r===e&&i.name==="objects";if(i.isDirectory()&&!s)t.push(We(r,i.name))}}finally{o.closeSync()}}return!1}catch(r){return r.code!=="ENOENT"}}function ky(e){try{return Es(Rn(e))}catch{return null}}function Es(e){let t=e;while(!0){let n=We(t,".git");if(yr(n))return n;let r=Vc(t);if(r===t)return null;t=r}}function Oy(e,t,n,r){if(Dy(t))return!0;if(n===null)return!0;let o=gy(n,["config","--get","submodule.recurse"],{cwd:e,encoding:"utf8",env:Ny(process.env),stdio:["ignore","pipe","ignore"],timeout:r});if(o.error!==void 0||o.status!==0&&o.status!==1)return null;return o.status===0&&Qc(o.stdout.trim())}function Dy(e){return[We(e.commonDir,"config"),We(e.gitDir,"config.worktree")].filter((t)=>yr(t)).some((t)=>Ly(t))}function My(){return Sy.find((e)=>yr(e))??null}function Cr(e){return e==="GIT_CONFIG_COUNT"||e==="GIT_CONFIG_PARAMETERS"||/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(e)}function Ny(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!Cr(t)))}function Ly(e){let t;try{t=Sr(e,"utf-8")}catch{return!0}let n="",r=!1;for(let o of t.split(/\r?\n/)){let i=o.trim();if(i===""||i.startsWith("#")||i.startsWith(";"))continue;let s=i.match(/^\[([^\]]+)\]$/);if(s){n=s[1]?.trim().toLowerCase()??"";continue}let a=i.indexOf("="),l=(a===-1?i:i.slice(0,a)).trim().toLowerCase(),c=a===-1?"true":i.slice(a+1).trim();if(Wy(n)&&l==="path")return!0;if(n==="submodule"&&l==="recurse")r=Qc(c)}return r}function Wy(e){return e==="include"||e.startsWith("includeif ")}function Qc(e){let t=e.toLowerCase();return t!=="false"&&t!=="no"&&t!=="off"&&t!=="0"}function Jc(e,t){if(e==="")return null;let n=Re(),r=Es(ge(e,e,t,n)),o=r?zy(r,e,t,n):null;if(!o)return null;return Object.freeze({entries:Object.freeze([o.entry]),markerFiles:Object.freeze(o.markerFile?[o.markerFile]:[]),directories:Object.freeze(o.directories),hooksDirectories:Object.freeze(o.hooksDirectories)})}function zy(e,t,n,r){try{let o=ge(e,t,n,r),i=Fy(e),s=i.isFile()?o:null,a=i.isFile()?vs(e):null,l=(i.isDirectory()?[o]:[a?.gitDir,a?.commonDir]).flatMap((d)=>d?[_n(ge(d,t,n,r))]:[]),c=[...new Set(i.isDirectory()?[_n(e.replace(/\\/g,"/")),...l]:l)];return{entry:_n(o),markerFile:s?_n(s):null,directories:c,hooksDirectories:[...new Set(c.flatMap((d)=>{let u=_n(Gy(d,"hooks").replace(/\\/g,"/"));return[u,_n(ge(u,t,n,r))]}))]}}catch{return null}}function _n(e){return process.platform==="win32"?e.toLowerCase():e}var Ky={realpath:(e)=>{try{let t=Uy(e);return jy(t)?t:null}catch{return null}},entryKind:(e)=>{try{let t=By(e,{throwIfNoEntry:!1});if(!t)return"missing";return t.isSymbolicLink()?"symlink":"present"}catch(t){if(t.code==="ENAMETOOLONG")return"missing";throw t}},isDirectory:(e)=>{try{return Hy(e).isDirectory()}catch{return!1}}};function ed(){let e=new Map;return Zy({env:new Map(Object.entries(process.env).flatMap(([t,n])=>n===void 0?[]:[[t,n]])),home:pe(process.env.HOME||Vy()),tmpdir:qy(),darwinUserTempDir:()=>ho(e,"",Yy),paths:Ky})}function Yy(){if(process.platform!=="darwin")return null;let e=$y("/usr/bin/getconf",["DARWIN_USER_TEMP_DIR"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1000}),t=e.stdout?.replace(/\n$/,"");return e.status===0&&t?.startsWith("/")?t:null}function Zy(e,t={}){let n=new Map,r=new Map,o=new Map,i={...e,gitMetadata:(s)=>ho(n,s,()=>Jc(s,i)),worktreeFacts:(s)=>ho(r,s,()=>qc(s)),isGitDirectory:Kc,gitDirectoryRedirects:(s)=>ho(o,s,()=>Yc(s)),...t};return i}function ho(e,t,n){let r=e.get(t);if(r!==void 0)return r;let o=n();return e.set(t,o),o}var xn=["fail_closed","paranoid_rm","paranoid_interpreters"],yo={standard:{fail_closed:!1,paranoid_rm:!1,paranoid_interpreters:!1},strict:{fail_closed:!0,paranoid_rm:!1,paranoid_interpreters:!1},paranoid:{fail_closed:!0,paranoid_rm:!0,paranoid_interpreters:!0}};var J={level:{name:"CC_SAFETY_NET_LEVEL"},strict:{name:"CC_SAFETY_NET_STRICT",legacyName:"SAFETY_NET_STRICT"},paranoid:{name:"CC_SAFETY_NET_PARANOID",legacyName:"SAFETY_NET_PARANOID"},paranoidRm:{name:"CC_SAFETY_NET_PARANOID_RM",legacyName:"SAFETY_NET_PARANOID_RM"},paranoidInterpreters:{name:"CC_SAFETY_NET_PARANOID_INTERPRETERS",legacyName:"SAFETY_NET_PARANOID_INTERPRETERS"},worktree:{name:"CC_SAFETY_NET_WORKTREE",legacyName:"SAFETY_NET_WORKTREE"},debug:{name:"CC_SAFETY_NET_DEBUG"},auditScope:{name:"CC_SAFETY_NET_AUDIT_SCOPE"},projectTightenOnly:{name:"CC_SAFETY_NET_PROJECT_TIGHTEN_ONLY"}},So=["standard","strict","paranoid"];function td(e,t){if(!t)return e;return So.indexOf(t)>So.indexOf(e)?t:e}function nd(e){let t=Co(J.level,e);return So.find((n)=>n===t)}function rd(e,t){return td(e,nd(t))}function Xy(e){let t=Co(J.level,e);if(!t)return;let n=nd(e);if(n)return n;console.error(`CC Safety Net: ignored invalid ${J.level.name}=${JSON.stringify(t.slice(0,40))}. Use ${So.join(", ")}.`);return}function Qy(e){if(e===void 0||e==="all")return"all";if(e==="blocked")return"blocked";return"invalid"}function od(e){return Qy(Co(J.auditScope,e))==="all"}function ws(e){if(e.failClosed&&e.paranoidRm&&e.paranoidInterpreters)return"paranoid";if(e.failClosed&&!e.paranoidRm&&!e.paranoidInterpreters)return"strict";if(!e.failClosed&&!e.paranoidRm&&!e.paranoidInterpreters)return"standard";return"custom"}function _s(e={},t){let n=e.safety?.level??"standard",r=Xy(t),o=td(n,r),i=yo[o],s={failClosed:i.fail_closed,paranoidRm:i.paranoid_rm,paranoidInterpreters:i.paranoid_interpreters},a={failClosed:o===n?"preset":"environment",paranoidRm:o===n?"preset":"environment",paranoidInterpreters:o===n?"preset":"environment"},l={failClosed:[`policy safety.level=${n}`],paranoidRm:[`policy safety.level=${n}`],paranoidInterpreters:[`policy safety.level=${n}`]};if(o!==n)l.failClosed.push(`env ${J.level.name}=${r}`),l.paranoidRm.push(`env ${J.level.name}=${r}`),l.paranoidInterpreters.push(`env ${J.level.name}=${r}`);if(e.safety?.overrides?.failClosed!==void 0)s.failClosed=e.safety.overrides.failClosed,a.failClosed="capability_override",l.failClosed.push("policy safety.overrides.fail_closed");if(e.safety?.overrides?.paranoidRm!==void 0)s.paranoidRm=e.safety.overrides.paranoidRm,a.paranoidRm="capability_override",l.paranoidRm.push("policy safety.overrides.paranoid_rm");if(e.safety?.overrides?.paranoidInterpreters!==void 0)s.paranoidInterpreters=e.safety.overrides.paranoidInterpreters,a.paranoidInterpreters="capability_override",l.paranoidInterpreters.push("policy safety.overrides.paranoid_interpreters");if(dt(J.strict,t))s.failClosed=!0,a.failClosed="environment",l.failClosed.push(`env ${J.strict.name}`);if(dt(J.paranoid,t))s.paranoidRm=!0,s.paranoidInterpreters=!0,a.paranoidRm="environment",a.paranoidInterpreters="environment",l.paranoidRm.push(`env ${J.paranoid.name}`),l.paranoidInterpreters.push(`env ${J.paranoid.name}`);if(dt(J.paranoidRm,t))s.paranoidRm=!0,a.paranoidRm="environment",l.paranoidRm.push(`env ${J.paranoidRm.name}`);if(dt(J.paranoidInterpreters,t))s.paranoidInterpreters=!0,a.paranoidInterpreters="environment",l.paranoidInterpreters.push(`env ${J.paranoidInterpreters.name}`);let c=!!e.worktreeMode||dt(J.worktree,t);return{strict:s.failClosed,paranoidRm:s.paranoidRm,paranoidInterpreters:s.paranoidInterpreters,worktreeMode:c,effectiveLevel:ws(s),capabilities:{fail_closed:{enabled:s.failClosed,source:a.failClosed,sources:l.failClosed},paranoid_rm:{enabled:s.paranoidRm,source:a.paranoidRm,sources:l.paranoidRm},paranoid_interpreters:{enabled:s.paranoidInterpreters,source:a.paranoidInterpreters,sources:l.paranoidInterpreters}}}}function dt(e,t){let n=typeof e==="string"?Rs(e,t):Co(e,t);return n==="1"||n?.toLowerCase()==="true"}function Rs(e,t){return t.get(e)}function Co(e,t){let n=Rs(e.name,t);if(n!==void 0)return n;if(e.legacyName)return Rs(e.legacyName,t);return}import{dirname as To}from"path";import{closeSync as Jy,constants as id,fstatSync as eS,fsyncSync as mD,lstatSync as Ps,mkdirSync as fD,openSync as tS,readdirSync as pD,readFileSync as nS,realpathSync as Ts,renameSync as gD,rmdirSync as hD,statSync as rS,unlinkSync as yD,writeFileSync as SD}from"fs";import{isAbsolute as sd,join as Is,normalize as oS,parse as As,relative as ks,resolve as Os,sep as Ds}from"path";function xs(){let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0");return`${e()}${e()}`}var iS=Symbol("PolicyFilesystemScope"),sS=Symbol("PolicyFilesystemTarget"),aS=id.O_NOFOLLOW??0;class he extends Error{name="PolicyFilesystemError";constructor(e){super(`Unable to access ${e} filesystem safely.`)}}function Bt(e,t){return{[iS]:!0,root:Os(e),label:t}}function ad(e,t){let n=oS(t);if(t===""||sd(t)||n===".."||n.startsWith(`..${Ds}`))throw new he(e.label);return{[sS]:!0,scope:e,relativePath:n,path:Is(e.root,n)}}function br(e,t){return ad(e,ks(e.root,Os(t)))}function ld(e,t="rules policy"){let n=Os(e),r=As(n).dir;return ad(Bt(r,t),ks(r,n))}function vo(e){return dd(e.scope.label,()=>{if(!bo(e))return null;let t=tS(e.path,id.O_RDONLY|aS);return lS(t,()=>{let n=eS(t);if(!n.isFile())throw new he(e.scope.label);let r=nS(t,"utf-8"),o=Ps(e.path);if(!o.isFile()||o.isSymbolicLink()||n.dev!==o.dev||n.ino!==o.ino)throw new he(e.scope.label);return bo(e),r})})}function cd(e,t){if(e.path===t.path)return!0;return dd(e.scope.label,()=>{if(!bo(e)||!bo(t))return!1;let n=(r)=>Is(Ts(As(r).dir),As(r).base);return n(e.path)===n(t.path)})}function dd(e,t,n){try{return t()}catch(r){if(n?.(),r instanceof he)throw r;throw new he(e)}}function lS(e,t){try{return t()}finally{Jy(e)}}function bo(e,t="file"){let n=cS(e.scope);if(!n)return!1;let r=e.relativePath.split(Ds);for(let o of r.keys()){let i=Is(e.scope.root,...r.slice(0,o+1)),s=Ps(i,{throwIfNoEntry:!1});if(!s)return!1;if(s.isSymbolicLink())throw new he(e.scope.label);if(o<r.length-1&&!s.isDirectory())throw new he(e.scope.label);if(o===r.length-1&&(t==="file"?!s.isFile():!s.isDirectory()))throw new he(e.scope.label);dS(n,Ts(i),e.scope.label)}return!0}function cS(e){if(!Ps(e.root,{throwIfNoEntry:!1}))return null;if(!rS(e.root).isDirectory())throw new he(e.label);return Ts(e.root)}function dS(e,t,n){let r=ks(e,t);if(r===".."||r.startsWith(`..${Ds}`)||sd(r))throw new he(n)}import{dirname as Ht,isAbsolute as gS,join as jt,relative as hS,resolve as _t,sep as yS}from"path";var Ut=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,ud="rulebook.json",md=".cc-safety-net/rules";var fd=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/;var uS=/^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/,mS=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),fS="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ED=new RegExp(`^${mS}/(${Ut.source.slice(1,-1)})/${fS}$`);function pS(e){return`.cc-safety-net/rules/${e}/rulebook.json`}function pd(e){if(Eo(e))try{return Ms(e),null}catch(t){return t instanceof Error?t.message:String(t)}return Ut.test(e)?null:`Local rulebook sources must be bare names matching ${Ut}: ${e}`}function Ms(e){if(e.startsWith("github:"))throw Error(`Invalid rulebook source: ${e}`);let t=e.match(fd);if(!t?.[1]||!t[2]||!t[3])throw Error(`Invalid GitHub rulebook source: ${e}`);let n=t[3].lastIndexOf("/");if(n<1)throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${e}`);let r=t[3].slice(0,n),o=t[3].slice(n+1);if(!r||!uS.test(r))throw Error(`GitHub rulebook refs must use valid path segments: ${e}`);if(!o||!Ut.test(o))throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${e}`);return{owner:t[1],repo:t[2],ref:r,path:pS(o),name:o}}function Eo(e){return fd.test(e)}var gd="rule.json",Ro="policy.json",hd=".cc-safety-net",SS="rules",CS="CC_SAFETY_NET_HOME",yd="`cc-safety-net rule update`";function bS(e){return _t(e,md)}function vS(e){return jt(bS(e),gd)}function An(e){return jt(_t(e),hd,Ro)}function Ns(e,t={}){return t.userConfigDir??(t.userConfigPath?Ht(t.userConfigPath):jt(ES(e),SS))}function ES(e){let t=e.env.get(CS);return t?_t(pe(t)):jt(e.home,hd)}function RS(e,t={}){return jt(Ns(e,t),gd)}function Vt(e,t={}){return jt(Ht(Ns(e,t)),Ro)}function Sd(e,t){let n=Re();return F(An(t.cwd),e.paths,n)===F(_t(Vt(e,t)),e.paths,n)}function Cd(e,t){let n=t.userConfigPath??RS(e,t),r=t.projectConfigPath??vS(t.cwd),o=wS(e,t),i=_S(r,t.cwd);return{userConfigPath:n,projectConfigPath:r,userScope:o,projectScope:i,userConfigTarget:br(o,n),projectConfigTarget:br(i,r)}}function wS(e,t){let n=t.userConfigPath?Ht(Ht(_t(t.userConfigPath))):Ht(_t(t.userConfigDir??Ns(e,t)));return Bt(n,"user policy")}function _S(e,t){let n=_t(t),r=_t(e),o=hS(n,r);if(o!==".."&&!o.startsWith(`..${yS}`)&&!gS(o))return Bt(n,"project policy");return Bt(Ht(Ht(r)),"project policy")}function bd(e,t){return jt(e,t,ud)}var Oe=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env"]),xt=/^[a-zA-Z][a-zA-Z0-9_-]*$/,At=256,Q=new Set(["bash","sh","zsh","ksh","dash","fish","csh","tcsh"]),vd=new Set(["python","python3","python2","node","ruby","perl"]),wo=/^python(?:[23](?:\.\d+)*)?$/,Fe=new Set(["awk","gawk","nawk","mawk"]),_o=new Set(["echo","printf","cat","head","tail","less","more","grep","rg","ag","ack","sed","awk","cut","tr","sort","uniq","wc","tee","man","help","info","type","which","whereis","whatis","apropos","file","stat","ls","ll","dir","tree","pwd","date","cal","uptime","whoami","id","groups","hostname","uname","env","printenv","set","export","alias","history","jobs","fg","bg","test","true","false","read","return","exit","break","continue","shift","wait","trap","basename","dirname","realpath","readlink","md5sum","sha256sum","base64","xxd","od","hexdump","strings","diff","cmp","comm","join","paste","column","fmt","fold","nl","pr","expand","unexpand","rev","tac","shuf","seq","yes","sleep","logger","write","wall","mesg","notify-send"]),xo=new Set(["curl","wget","aria2c","http","https","xh","xhs","httpie","fetch","lwp-request","nc","ncat","netcat","socat","telnet"]);var Ed="Rulebook exceeds CC Safety Net's safe validation limits.",Rd="Additional rulebook validation errors were omitted.",Ue=Object.freeze({maxAllowedCommands:1024,maxRules:1024,maxTests:2048,maxBlockArgsPerRule:1024,maxTotalBlockArgs:16384,maxStringCodeUnits:1048576,maxAggregateStringCodeUnits:4194304,maxFixtureCommandCodeUnits:131072,maxValidationErrors:64});function wd(e){if(Ls(e.allowed_commands,Ue.maxAllowedCommands)||Ls(e.rules,Ue.maxRules)||Ls(e.tests,Ue.maxTests))return!1;let{maxAggregateStringCodeUnits:t,maxTotalBlockArgs:n}=Ue,r=(o,i=!1)=>{if(typeof o!=="string")return!0;if(o.length>Ue.maxStringCodeUnits||i&&o.length>Ue.maxFixtureCommandCodeUnits||o.length>t)return!1;return t-=o.length,!0};if(!r(e.name)||!r(e.version)||!r(e.description)||!r(e.author)||!r(e.migrated_from))return!1;if(Array.isArray(e.allowed_commands)){for(let o of e.allowed_commands)if(!r(o))return!1}if(Array.isArray(e.rules))for(let o of e.rules){if(!o||typeof o!=="object")continue;let i=o;if(!r(i.name)||!r(i.command)||!r(i.subcommand)||!r(i.reason)||!r(i.intent))return!1;let s=i.match&&typeof i.match==="object"?i.match:{};for(let a of[i.block_args,s.command_path,s.any_args,s.exclude_args]){if(!Array.isArray(a))continue;if(a.length>Ue.maxBlockArgsPerRule||a.length>n)return!1;n-=a.length;for(let l of a)if(!r(l))return!1}}if(Array.isArray(e.tests))for(let o of e.tests){if(!o||typeof o!=="object")continue;let i=o;if(!r(i.command,!0)||!r(i.expect)||!r(i.rule))return!1}return!0}function Ls(e,t){return Array.isArray(e)&&e.length>t}var Ws=Object.freeze(["hard_stop","use_alternative","scope_down","manual_only","stop_and_explain"]);var Fs=64,Gs="Rule config exceeds CC Safety Net's safe source limit.";function N(e){return k(e).toLowerCase()}function k(e){return e.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??e}function we(e,t){let n=new Set,r=!1;for(let o of e){if(o==="--"){r=!0;continue}if(r)continue;if(o.startsWith("-")&&!o.startsWith("--")&&o.length>1)for(let i=1;i<o.length;i++){let s=o[i];if(!s||!/[a-zA-Z]/.test(s))break;let a=`-${s}`;if(n.add(a),t?.shortOptsWithValue?.has(a))break}}return n}var xS={bash:["O","o"],dash:["o"],ksh:["o"],sh:["o"],zsh:["o"]},zs=new Set(["--init-file","--rcfile"]);function $s(e,t,n,r){let o=!1,i=0,s=!1,a=!1;for(let l=1;l<t.length;l++){let c=t[l];if(c===void 0)break;if(e==="ksh"&&c==="o"&&l+1<t.length){if(r==="argv"){let d=t.slice(l+1);if(t[0]==="-"&&(d==="c"||d[0]==="-"&&d.endsWith("c")))s=!0}break}if(e==="ksh"&&c==="o"&&l+1===t.length&&(n?.startsWith("-")||n?.startsWith("+")))break;if(e==="zsh"&&c==="o"&&l+1<t.length)break;if(r==="startup"&&c==="i")o=t[0]==="-";if(r==="argv"&&t[0]==="-"&&c==="c")s=!0;if(r==="argv"&&c==="s")a=t[0]==="-";if(!xS[e]?.includes(c))continue;if(l+1===t.length)i++;break}return{interactive:o,followingValues:i,commandSelected:s,stdinMode:a}}function _e(e){let t=k(e[0]??"").toLowerCase(),n=!1,r=!1;for(let o=1;o<e.length;o++){let i=e[o];if(i===void 0)break;if(i==="--"){let a=n&&e[o+1]!==void 0?o+1:null;return{command:a===null?null:e[a]??null,commandIndex:a,scriptIndex:!n&&!r&&e[o+1]!==void 0?o+1:null,readsStdinAsCommands:!n&&(r||e[o+1]===void 0)}}if(i==="-"||i[0]!=="-"&&i[0]!=="+")return{command:n?i:null,commandIndex:n?o:null,scriptIndex:!n&&!r&&i!=="-"?o:null,readsStdinAsCommands:!n&&(r||i==="-")};if(i.startsWith("--")){let a=i.split("=",1)[0]??i;if(t==="bash"&&zs.has(a)&&!i.includes("="))o++;continue}let s=$s(t,i,e[o+1],"argv");if(s.commandSelected)n=!0;if(s.stdinMode)r=!0;o+=s.followingValues}return{command:null,commandIndex:null,scriptIndex:null,readsStdinAsCommands:!n}}function vr(e,t){if(t.escaped)return t.escaped=!1,!0;if(e==="\\"&&!t.inSingle)return t.escaped=!0,!0;if(e==="'"&&!t.inDouble)return t.inSingle=!t.inSingle,!0;if(e==='"'&&!t.inSingle)return t.inDouble=!t.inDouble,!0;return!1}function Ao(e){let t={inSingle:!1,inDouble:!1,escaped:!1};for(let n of AS(e))vr(n,t);return t.inSingle||t.inDouble}function AS(e){let t="",n={inSingle:!1,inDouble:!1,escaped:!1},r=!1,o=!0;for(let i=0;i<e.length;i++){let s=e[i];if(!s)break;if(r){if(s===`
8
- `||s==="\r")t+=s,r=!1,n.escaped=!1;continue}if(s==="#"&&!n.inSingle&&!n.inDouble&&o){r=!0;continue}if(t+=s,!n.inSingle&&!n.inDouble&&!n.escaped)o=/[\s;&|()<>]/.test(s);vr(s,n)}return t}var Bs=new Set(["rm","find","rsync","xargs","parallel"]),PS=new Set(["git","busybox",...Bs,...Q,...vd,...Fe]),TS=new Set(["python","node","ruby","perl"]);function _d(e){let t=N(e);return PS.has(t)||De(t)}function De(e){return TS.has(IS(e))}function IS(e){let t=k(e).toLowerCase();return wo.test(t)?"python":t}function js(e){try{let t=vo(kS(e));if(t===null)return{config:null,errors:[]};if(!t.trim())return{config:null,errors:["Config file is empty"]};let n=JSON.parse(t),r=NS(n);if(r.errors.length>0)return{config:null,errors:r.errors};return{config:{version:1,rules:n.rules??[],overrides:n.overrides??{},transparent_wrappers:n.transparent_wrappers??[],...n.command_tools?{command_tools:n.command_tools}:{}},errors:[]}}catch(t){if(t instanceof he)return{config:null,errors:[t.message]};let n=t instanceof Error?t.message:String(t);return{config:null,errors:[t instanceof SyntaxError?"Invalid JSON":n]}}}function kS(e){return typeof e==="string"?ld(e):e}var T=(e,t)=>({path:e,message:t,kind:"typed"}),se=(e,t)=>({path:e,message:t,kind:"custom"});function xd(e){let t=new Set;return e.flatMap((n,r)=>{let o=qt(n)?n.name:void 0;if(typeof o!=="string")return[];if(t.has(o.toLowerCase()))return[se(["rules",r,"name"],`duplicate rule name "${o}"`)];return t.add(o.toLowerCase()),[]})}var Vs=`must be one of ${Ws.join(", ")}`,OS=/^[^/]+\/[^/]+$/,DS=["version","rules","overrides","transparent_wrappers","command_tools"],MS=/^[^\s\p{Cc}]{1,256}$/u,Us="non-empty, at most 256 characters, no whitespace or control characters";function NS(e){let t=LS(e);return{errors:qs(VS(t,DS,(n)=>n.kind==="custom"),": "," "),sources:jS(e,t)}}function LS(e){if(!qt(e))return[T([],"Config must be an object")];let t=Array.isArray(e.rules)&&e.rules.length>Fs;return[...e.version===1?[]:[T(["version"],"must be 1")],...WS(e.rules,t),...zS(e.overrides),...BS(e.transparent_wrappers),...t?[]:GS(e.rules),...qt(e.overrides)?Object.keys(e.overrides).filter((n)=>!OS.test(n)).map((n)=>se(["overrides",n],"must use <rulebook-name>/<rule-name>")):[],...US(e.transparent_wrappers),...HS(e.command_tools)]}function WS(e,t){if(e===void 0)return[];if(!Array.isArray(e))return[T(["rules"],"must be an array of rulebook source strings"),...Ad(e,Fs)?[T(["rules"],Gs)]:[]];if(t)return[{path:["rules"],message:Gs,kind:"limit"}];return e.flatMap((n,r)=>{if(typeof n!=="string")return[T(["rules",r],"must be a rulebook source string"),...FS(n,1)?[T(["rules",r],"must be a non-empty rulebook source string")]:[]];return n===""?[T(["rules",r],"must be a non-empty rulebook source string")]:[]})}function Ad(e,t){let n=Pd(e);return n!==void 0&&!(n<=t)}function FS(e,t){let n=Pd(e);return n!==void 0&&!(n>=t)}function Pd(e){if(e===null||e===void 0)return;let t=e.length;return t===void 0?void 0:Number(t)}function GS(e){if(!Array.isArray(e))return[];let t=new Set;return e.flatMap((n,r)=>{if(typeof n!=="string"||n==="")return[];if(n.trim()==="")return[se(["rules",r],"must be a non-empty rulebook source string")];let o=pd(n);if(o)return[se(["rules",r],o)];if(t.has(n))return[se(["rules",r],`duplicate rulebook source "${n}"`)];return t.add(n),[]})}function zS(e){if(e===void 0)return[];if(!qt(e))return[T(["overrides"],"must be an object if provided")];return Object.keys(e).flatMap((t)=>{let n=e[t];if(n==="off")return[];if(!qt(n))return[T(["overrides",t],'must be "off" or an object')];return[...$S(n.reason,["overrides",t,"reason"]),...n.intent===void 0||Ys(n.intent)?[]:[T(["overrides",t,"intent"],Vs)]]})}function $S(e,t){if(typeof e!=="string")return[T(t,"required non-empty string"),...Ad(e,At)?[T(t,`must be at most ${At} characters`)]:[]];if(e==="")return[T(t,"required non-empty string")];return e.length>At?[T(t,`must be at most ${At} characters`)]:[]}function BS(e){if(e===void 0)return[];if(!Array.isArray(e))return[T(["transparent_wrappers"],"must be an array of command strings")];return e.flatMap((t,n)=>{if(typeof t!=="string")return[T(["transparent_wrappers",n],"must be a command string")];return xt.test(t)?[]:[T(["transparent_wrappers",n],"must match command pattern")]})}function US(e){if(!Array.isArray(e))return[];let t=new Set;return e.flatMap((n,r)=>{if(typeof n!=="string"||!xt.test(n))return[];if(t.has(n))return[se(["transparent_wrappers",r],`duplicate command "${n}"`)];if(_d(n))return[se(["transparent_wrappers",r],`reserved command "${n}" cannot be a wrapper`)];return t.add(n),[]})}function HS(e){if(e===void 0)return[];if(!Array.isArray(e))return[T(["command_tools"],"must be an array of tool names or {name, cwd} objects")];let t=new Set,n=(r,o)=>{if(t.has(r))return[se(["command_tools",o],`duplicate tool "${r}"`)];return t.add(r),[]};return e.flatMap((r,o)=>{if(typeof r==="string")return Hs(r)?n(r,o):[T(["command_tools",o],`must be a tool name: ${Us}`)];if(!qt(r))return[T(["command_tools",o],"must be a tool name or a {name, cwd} object")];let i=[...Hs(r.name)?[]:[T(["command_tools",o,"name"],`must be a tool name: ${Us}`)],...r.cwd===void 0||Hs(r.cwd)?[]:[T(["command_tools",o,"cwd"],`must be an argument name: ${Us}`)]];return i.length>0?i:n(r.name,o)})}function Hs(e){return typeof e==="string"&&MS.test(e)}function jS(e,t){let n=qt(e)?e.rules:void 0;if(!Array.isArray(n))return new Set;if(t.some((o)=>o.path.length===1&&o.path[0]==="rules"))return new Set;let r=new Set(t.filter((o)=>o.path[0]==="rules"&&typeof o.path[1]==="number").map((o)=>o.path[1]));return new Set(n.filter((o,i)=>typeof o==="string"&&!r.has(i)))}function VS(e,t,n){let r=e.map((s)=>s.path[1]),o=[...new Set(r.filter((s)=>typeof s==="string"))],i=(s,a)=>[s.path.length===0?-1:t.indexOf(String(s.path[0])),typeof a==="number"?a:o.indexOf(String(a)),n(s)?0:1];return e.map((s,a)=>({issue:s,rank:i(s,r[a])})).sort((s,a)=>s.rank[0]-a.rank[0]||s.rank[1]-a.rank[1]||s.rank[2]-a.rank[2]).map((s)=>s.issue)}function qs(e,t,n){return[...new Set(e.map((r)=>{let o=Ks(r.path);if(r.kind==="unknownKeys")return`${o?`${o}.`:""}unknown field "${r.message}"`;if(r.kind==="key"||r.kind==="limit"||r.path.length===0)return r.message;return`${o}${r.path.length===1?n:t}${r.message}`}))]}function Ks(e){return e.map((t,n)=>{if(typeof t==="number")return`[${t}]`;return n===0?String(t):`.${String(t)}`}).join("")}function Ys(e){return Ws.includes(e)}function qt(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function Id(e){let t=YS(e);if(t.errors.length>0)throw Error(t.errors.join("; "));return e}var qS=`required non-empty string up to ${At} characters`,Td="must be a non-empty array of unique non-empty strings",KS="required non-empty array of non-empty strings";function YS(e){if(!Pt(e))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!wd(e))return{errors:[Ed],ruleNames:new Set};let t=[...e.rulebook_version===1||e.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],...qs(ZS(e,e.rulebook_version===2),": ",": ")];return{errors:t.length>Ue.maxValidationErrors?[...t.slice(0,Ue.maxValidationErrors),Rd]:t,ruleNames:new Set(kd(e).map((n)=>n.toLowerCase()))}}function kd(e){let t=Pt(e)?e.rules:void 0;return(Array.isArray(t)?t:[]).flatMap((n)=>{let r=Pt(n)?n.name:void 0;return typeof r==="string"?[r]:[]})}function ZS(e,t){return[...typeof e.name==="string"&&Ut.test(e.name)?[]:[T(["name"],"required string matching rule name pattern")],...typeof e.version==="string"&&e.version!==""?[]:[T(["version"],"required non-empty string")],...XS(e.allowed_commands),...QS(e.rules,t),...nC(e.tests),...rC(e),...oC(e)]}function XS(e){if(!Array.isArray(e))return[T(["allowed_commands"],"required array")];let t=new Set;return[...e.flatMap((n,r)=>typeof n==="string"&&xt.test(n)?[]:[T(["allowed_commands",r],"must match command pattern")]),...e.flatMap((n,r)=>{if(typeof n!=="string"||!xt.test(n))return[];if(t.has(n))return[se(["allowed_commands",r],`duplicate command "${n}"`)];return t.add(n),[]})]}function QS(e,t){if(!Array.isArray(e))return[T(["rules"],"required array")];return[...e.flatMap((n,r)=>{if(!Pt(n))return[T(["rules",r],"must be an object")];return t?eC(n,["rules",r]):JS(n,["rules",r])}),...xd(e)]}function JS(e,t){return[...Od(e.name,t),...Dd(e.command,t),...e.subcommand===void 0||typeof e.subcommand==="string"&&xt.test(e.subcommand)?[]:[T([...t,"subcommand"],"must match command pattern")],...Po(e.block_args,[...t,"block_args"],"required non-empty array",!1),...Md(e.reason,t),...Nd(e.intent,t)]}function eC(e,t){return[...Od(e.name,t),...Dd(e.command,t),...Md(e.reason,t),...Nd(e.intent,t),...tC(e.match,[...t,"match"]),...e.subcommand===void 0?[]:[T([...t,"subcommand"],"not supported in rulebook_version 2")],...e.block_args===void 0?[]:[T([...t,"block_args"],"not supported in rulebook_version 2")]]}function Od(e,t){if(typeof e!=="string")return[T([...t,"name"],"required string")];return Ut.test(e)?[]:[T([...t,"name"],"must match rule name pattern")]}function Dd(e,t){return typeof e==="string"&&xt.test(e)?[]:[T([...t,"command"],"required string matching command pattern")]}function Md(e,t){return typeof e==="string"&&e!==""&&e.length<=At?[]:[T([...t,"reason"],qS)]}function Nd(e,t){return e===void 0||Ys(e)?[]:[T([...t,"intent"],Vs)]}function tC(e,t){if(!Pt(e))return[T(t,"required object")];return[...Po(e.command_path,[...t,"command_path"],KS,!1),...e.any_args===void 0?[]:Po(e.any_args,[...t,"any_args"],Td,!0),...e.exclude_args===void 0?[]:Po(e.exclude_args,[...t,"exclude_args"],Td,!0)]}function Po(e,t,n,r){if(!Array.isArray(e))return[T(t,n)];let o=e.flatMap((i,s)=>{if(typeof i!=="string")return[T([...t,s],"must be a non-empty string")];return i===""?[se([...t,s],"must be a non-empty string")]:[]});if(e.some((i)=>typeof i!=="string"))return o;return[...o,...e.length===0?[se(t,n)]:[],...r&&new Set(e).size!==e.length?[se(t,"must not contain duplicate values")]:[]]}function nC(e){if(e===void 0)return[];if(!Array.isArray(e))return[T(["tests"],"must be an array if provided")];return e.flatMap((t,n)=>{if(!Pt(t))return[T(["tests",n],"must be an object")];return[...typeof t.command==="string"&&t.command.trim()!==""?[]:[T(["tests",n,"command"],"required non-empty string")],...t.expect==="blocked"||t.expect==="allowed"?[]:[T(["tests",n,"expect"],'must be "blocked" or "allowed"')],...t.rule===void 0||typeof t.rule==="string"?[]:[T(["tests",n,"rule"],"must be a string if provided")],...t.expect==="blocked"&&typeof t.rule!=="string"?[se(["tests",n,"rule"],"required string for blocked fixtures")]:[]]})}function rC(e){if(!Array.isArray(e.tests))return[];let t=new Set(kd(e));return[...new Set(e.tests.flatMap((n)=>Pt(n)&&n.expect==="blocked"&&typeof n.rule==="string"?[n.rule]:[]))].filter((n)=>!t.has(n)).map((n)=>se(["tests"],`blocked fixture references unknown rule "${n}"`))}function oC(e){if(!Array.isArray(e.allowed_commands)||!Array.isArray(e.rules))return[];let t=new Set(e.allowed_commands.filter((n)=>typeof n==="string"));return e.rules.flatMap((n,r)=>{let o=Pt(n)?n.command:void 0;if(typeof o!=="string"||t.has(o))return[];return[se(["rules",r,"command"],`"${o}" must be listed in allowed_commands`)]})}function Pt(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function Bd(e,t){let n=Cd(e,t),r;try{r=cd(n.userConfigTarget,n.projectConfigTarget)}catch(m){if(m instanceof he)return pC(n,m.message);throw m}let o=js(n.userConfigTarget),i=r?{config:null,errors:[]}:js(n.projectConfigTarget),s=zd(n.userConfigPath,o.errors),a=zd(n.projectConfigPath,i.errors),l=new Set,c=o.config?Ld(o.config,To(n.userConfigPath),"user",n.userScope,l):$d(),d=i.config?Ld(i.config,To(n.projectConfigPath),"project",n.projectScope,l):$d(),u=o.config?.overrides??{},f=i.config?.overrides??{};return{rules:[...Fd(c.rules,u),...Fd(d.rules,f)],transparent_wrappers:uC(o.config,i.config),command_tools:mC(o.config,i.config),rulebooks:[...c.rulebooks,...d.rulebooks],errors:[...s,...a,...c.errors,...d.errors],warnings:[...c.warnings,...d.warnings,...c.canValidateOverrides?Gd(u,c.knownRuleIds,n.userConfigPath):[],...c.canValidateOverrides?fC(f,c.knownRuleIds,n.projectConfigPath):[],...d.canValidateOverrides?Gd(f,d.knownRuleIds,n.projectConfigPath):[]],userConfig:o.config??void 0,projectConfig:i.config??void 0,...n}}function Ld(e,t,n,r=Bt(To(To(t)),n==="user"?"user policy":"project policy"),o=new Set){let i=[],s=[],a=e.rules.flatMap((c)=>{let d=sC(c,t,r);if(d.errors.length>0||!d.rulebook)return i.push(...d.errors),[];let u=d.rulebook;if(o.has(u.name))return s.push(`duplicate active rulebook name "${u.name}" for ${c}; keeping the first and ignoring this one, so its rules are not active; rename one of them in its rulebook file and in the rules config that lists it`),[];return o.add(u.name),[{rules:iC(u),rulebook:{source:n,spec:c,name:u.name,version:u.version,rules:u.rules.map((f)=>`${u.name}/${f.name}`)}}]}),l=a.flatMap((c)=>c.rules);return{rules:l,rulebooks:a.map((c)=>c.rulebook),knownRuleIds:new Set(l.map((c)=>c.name)),errors:i,warnings:s,canValidateOverrides:i.length===0}}function iC(e){if(e.rulebook_version===2)return e.rules.map((t)=>({name:`${e.name}/${t.name}`,command:t.command,block_args:[],match:t.match,reason:t.reason,intent:t.intent}));return e.rules.map((t)=>({...t,name:`${e.name}/${t.name}`,match:void 0}))}function sC(e,t,n){let r=aC(e),o=bd(t,r),i=cC(o,n);if("error"in i)return{rulebook:null,errors:[i.error]};if(i.content===null)return{rulebook:null,errors:[`missing rulebook file ${o} for ${e}; ${lC(e)}`]};let s=dC(i.content);if("problem"in s)return{rulebook:null,errors:[`invalid rulebook ${o}: ${s.problem}; fix that file`]};if(s.rulebook.name!==r)return{rulebook:null,errors:[`rulebook name "${s.rulebook.name}" in ${o} must match source "${e}"; fix that file`]};return{rulebook:s.rulebook,errors:[]}}function aC(e){return Eo(e)?Ms(e).name:e}function lC(e){return Eo(e)?`run ${yd} to vendor ${e}`:"create that file or remove that source from the rules config"}function cC(e,t){try{return{content:vo(br(t,e))}}catch(n){if(n instanceof he)return{error:n.message};throw n}}function dC(e){let t;try{t=JSON.parse(e)}catch{return{problem:"Invalid JSON"}}try{return{rulebook:Id(t)}}catch(n){return{problem:n instanceof Error?n.message:"invalid rulebook"}}}function uC(e,t){return[...new Set([...e?.transparent_wrappers??[],...t?.transparent_wrappers??[]])]}function mC(e,t){let n=(e?.command_tools??[]).map(Wd),r=(t?.command_tools??[]).map(Wd);return[...n,...r.filter((o)=>!n.some((i)=>i.name===o.name))]}function Wd(e){if(typeof e==="string")return{name:e};return e.cwd===void 0?{name:e.name}:{name:e.name,cwd:e.cwd}}function Fd(e,t){return e.flatMap((n)=>{let r=t[n.name];if(r==="off")return[];if(r&&typeof r==="object")return[{...n,intent:r.intent??n.intent,reason:r.reason}];return[n]})}function Gd(e,t,n){return Object.keys(e).filter((r)=>!t.has(r)).map((r)=>`unknown override key "${r}" in ${n}; only that override is ignored and other overrides and rules keep their configured state; correct or remove it in that file`)}function fC(e,t,n){return Object.keys(e).filter((r)=>t.has(r)).map((r)=>`project override cannot target user-scoped rule "${r}" in ${n}; only that override is ignored and the rule keeps its user-configured state; remove it from that file`)}function zd(e,t){return t.map((n)=>n.startsWith("Unable to access ")?n:`${e}: ${n}`)}function pC(e,t){return{rules:[],transparent_wrappers:[],command_tools:[],rulebooks:[],errors:[t],warnings:[],userConfigPath:e.userConfigPath,projectConfigPath:e.projectConfigPath}}function $d(){return{rules:[],rulebooks:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}import{existsSync as xC,readFileSync as AC}from"fs";var Ud=[{id:"git.ssh-env",category:"Git",label:"Git SSH environment override",description:"Blocks Git network operations with SSH environment overrides.",example:'GIT_SSH_COMMAND="./ssh-wrapper" git push',intent:"manual_only"},{id:"git.alias-config",category:"Git",label:"Git command-line alias",description:"Blocks command-line Git aliases that cannot be safely resolved.",example:"git -c alias.wipe='!rm -rf /' wipe",intent:"manual_only"},{id:"git.checkout-force",category:"Git",label:"Git checkout force",description:"Blocks forced checkout operations that discard local changes.",example:"git checkout --force main",intent:"use_alternative"},{id:"git.checkout-double-dash",category:"Git",label:"Git checkout path restore",description:"Blocks checkout path restores, with or without --.",example:"git checkout -- src/app.ts",intent:"use_alternative"},{id:"git.checkout-ref-path",category:"Git",label:"Git checkout ref and path",description:"Blocks checkout forms that mix a ref and path restore.",example:"git checkout HEAD -- src/app.ts",intent:"use_alternative"},{id:"git.checkout-pathspec-from-file",category:"Git",label:"Git checkout pathspec file",description:"Blocks checkout pathspec loading from a file.",example:"git checkout --pathspec-from-file=paths.txt",intent:"use_alternative"},{id:"git.checkout-ambiguous",category:"Git",label:"Git checkout ambiguous targets",description:"Blocks ambiguous checkout arguments that may restore paths.",example:"git checkout main src/app.ts",intent:"use_alternative"},{id:"git.switch-discard-changes",category:"Git",label:"Git switch discard changes",description:"Blocks branch switches that explicitly discard local changes.",example:"git switch --discard-changes main",intent:"use_alternative"},{id:"git.switch-force",category:"Git",label:"Git switch force",description:"Blocks forced branch switches.",example:"git switch --force main",intent:"use_alternative"},{id:"git.restore-worktree",category:"Git",label:"Git restore worktree",description:"Blocks worktree restore operations.",example:"git restore --worktree src/app.ts",intent:"use_alternative"},{id:"git.restore-unstaged",category:"Git",label:"Git restore unstaged",description:"Blocks unstaged restore operations.",example:"git restore src/app.ts",intent:"use_alternative"},{id:"git.reset-hard",category:"Git",label:"Git reset hard",description:"Blocks hard resets.",example:"git reset --hard",intent:"use_alternative"},{id:"git.reset-merge",category:"Git",label:"Git reset merge",description:"Blocks merge resets.",example:"git reset --merge",intent:"use_alternative"},{id:"git.clean-force",category:"Git",label:"Git clean force",description:"Blocks forced clean operations.",example:"git clean -fd",intent:"use_alternative"},{id:"git.rm-force",category:"Git",label:"Git rm force",description:"Blocks forced removal of tracked files from the working tree.",example:"git rm -rf .",intent:"use_alternative"},{id:"git.push-force",category:"Git",label:"Git push force",description:"Blocks force pushes.",example:"git push --force origin main",intent:"use_alternative"},{id:"git.push-delete",category:"Git",label:"Git push delete",description:"Blocks remote ref deletion through push.",example:"git push --delete origin old-branch",intent:"manual_only"},{id:"git.push-mirror",category:"Git",label:"Git push mirror",description:"Blocks mirror pushes that can force-update or delete remote refs.",example:"git push --mirror origin",intent:"manual_only"},{id:"git.branch-force-delete",category:"Git",label:"Git branch force delete",description:"Blocks forced branch deletion.",example:"git branch -D old-branch",intent:"use_alternative"},{id:"git.rebase-abort",category:"Git",label:"Git rebase abort",description:"Blocks rebase abort operations.",example:"git rebase --abort",intent:"use_alternative"},{id:"git.merge-abort",category:"Git",label:"Git merge abort",description:"Blocks merge abort operations.",example:"git merge --abort",intent:"use_alternative"},{id:"git.tag-delete",category:"Git",label:"Git tag delete",description:"Blocks tag deletion.",example:"git tag --delete v1.0.0",intent:"manual_only"},{id:"git.reflog-delete",category:"Git",label:"Git reflog delete",description:"Blocks reflog deletion.",example:"git reflog delete HEAD@{1}",intent:"manual_only"},{id:"git.stash-drop",category:"Git",label:"Git stash drop",description:"Blocks dropping stash entries.",example:"git stash drop stash@{0}",intent:"use_alternative"},{id:"git.stash-clear",category:"Git",label:"Git stash clear",description:"Blocks clearing all stash entries.",example:"git stash clear",intent:"manual_only"},{id:"git.worktree-remove-force",category:"Git",label:"Git worktree force remove",description:"Blocks forced worktree removal.",example:"git worktree remove --force ../feature",intent:"use_alternative"},{id:"rm.recursive-force-root-or-home",category:"Filesystem",label:"rm -rf root or home",description:"Blocks recursive forced removal of root or home paths.",example:"rm -rf /",intent:"hard_stop",catastrophic:!0},{id:"rm.git-metadata",category:"Filesystem",label:"rm Git metadata",description:"Blocks removal of protected Git metadata and hooks.",example:"rm -rf .git",intent:"hard_stop",catastrophic:!0},{id:"rm.recursive-force-dynamic-target",category:"Filesystem",label:"rm -rf dynamic target",description:"Blocks recursive forced removal with dynamic targets in strict mode.",example:'rm -rf "$target"',intent:"scope_down",activationCapability:"fail_closed"},{id:"rm.recursive-force-home-cwd",category:"Filesystem",label:"rm -rf from home cwd",description:"Blocks recursive forced removal while working in home.",example:'cd "$HOME" && rm -rf build',intent:"scope_down"},{id:"rm.recursive-force-cwd-self",category:"Filesystem",label:"rm -rf current directory",description:"Blocks recursive forced removal of the current directory.",example:"rm -rf .",intent:"scope_down"},{id:"rm.recursive-force-outside-cwd",category:"Filesystem",label:"rm -rf outside cwd",description:"Blocks recursive forced removal outside the original cwd.",example:"rm -rf ../outside",intent:"scope_down"},{id:"rm.recursive-force-paranoid",category:"Filesystem",label:"rm -rf paranoid mode",description:"Blocks non-temp recursive forced removal when paranoid rm is enabled.",example:"rm -rf ./cache",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"powershell.remove-item-root-or-home",category:"PowerShell",label:"Remove-Item root or home",description:"Blocks PowerShell Remove-Item targeting root or home paths.",example:"Remove-Item C:\\",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-recursive-force-root-or-home",category:"PowerShell",label:"Remove-Item recursive force root or home",description:"Blocks recursive forced PowerShell removal of root or home paths.",example:"Remove-Item C:\\ -Recurse -Force",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-git-metadata",category:"PowerShell",label:"Remove-Item Git metadata",description:"Blocks PowerShell removal of protected Git metadata and hooks.",example:"Remove-Item .git -Recurse -Force",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-recursive-force-dynamic-target",category:"PowerShell",label:"Remove-Item recursive force dynamic target",description:"Blocks recursive forced PowerShell removal with dynamic targets in strict mode.",example:"Remove-Item $target -Recurse -Force",intent:"scope_down",activationCapability:"fail_closed"},{id:"powershell.remove-item-recursive-force-home-cwd",category:"PowerShell",label:"Remove-Item recursive force from home cwd",description:"Blocks recursive forced PowerShell removal while working in home.",example:"Set-Location $HOME; Remove-Item ./build -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-cwd-self",category:"PowerShell",label:"Remove-Item recursive force current directory",description:"Blocks recursive forced PowerShell removal of the current directory.",example:"Remove-Item . -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-outside-cwd",category:"PowerShell",label:"Remove-Item recursive force outside cwd",description:"Blocks recursive forced PowerShell removal outside the original cwd.",example:"Remove-Item ../outside -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-paranoid",category:"PowerShell",label:"Remove-Item recursive force paranoid mode",description:"Blocks non-temp recursive forced PowerShell removal when paranoid rm is enabled.",example:"Remove-Item ./cache -Recurse -Force",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"powershell.remove-item-pipeline-dynamic-target",category:"PowerShell",label:"Remove-Item pipeline dynamic target",description:"Blocks PowerShell Remove-Item with unverifiable pipeline input in strict mode.",example:"Get-ChildItem . -Recurse | Remove-Item -Force",intent:"scope_down",activationCapability:"fail_closed"},{id:"powershell.nested-recursive-delete-unread",category:"PowerShell",label:"Nested PowerShell recursive delete not read",description:"Blocks a recursive delete handed to powershell or pwsh in any form other than literal -Command script words.",example:"pwsh -WorkingDirectory C:\\ -c 'Remove-Item -Recurse -Force *'",intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-root-or-home",category:"Command Prompt",label:"cmd recursive delete root or home",description:"Blocks cmd rmdir /s or del /s of root or home paths.",example:"cmd /c rmdir /s /q C:\\",intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-escaped-quote",category:"Command Prompt",label:"cmd recursive delete with escaped quotes",description:"Blocks cmd rmdir /s or del /s whose quoting can reach cmd as \\\" and split the target down to the drive root.",example:'cmd /c "rmdir /s /q \\"build output\\""',intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-git-metadata",category:"Command Prompt",label:"cmd recursive delete Git metadata",description:"Blocks cmd rmdir /s or del /s of protected Git metadata and hooks.",example:"cmd /c rmdir /s /q .git",intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-dynamic-target",category:"Command Prompt",label:"cmd recursive delete dynamic target",description:"Blocks cmd rmdir /s or del /s with wildcard or variable targets in strict mode.",example:"cmd /c del /s /q *.log",intent:"scope_down",activationCapability:"fail_closed"},{id:"cmd.recursive-delete-home-cwd",category:"Command Prompt",label:"cmd recursive delete from home cwd",description:"Blocks cmd rmdir /s or del /s while working in home.",example:"Set-Location $HOME; cmd /c rmdir /s /q build",intent:"scope_down"},{id:"cmd.recursive-delete-cwd-self",category:"Command Prompt",label:"cmd recursive delete current directory",description:"Blocks cmd rmdir /s or del /s of the current directory.",example:"cmd /c rmdir /s /q .",intent:"scope_down"},{id:"cmd.recursive-delete-outside-cwd",category:"Command Prompt",label:"cmd recursive delete outside cwd",description:"Blocks cmd rmdir /s or del /s outside the original cwd.",example:"cmd /c rmdir /s /q ..\\outside",intent:"scope_down"},{id:"cmd.recursive-delete-paranoid",category:"Command Prompt",label:"cmd recursive delete paranoid mode",description:"Blocks non-temp cmd rmdir /s or del /s when paranoid rm is enabled.",example:"cmd /c rmdir /s /q build",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"find.delete",category:"Filesystem",label:"find delete",description:"Blocks unsafe find -delete operations.",example:"find . -delete",intent:"scope_down"},{id:"find.delete-git-metadata",category:"Filesystem",label:"find delete Git metadata",description:"Blocks find -delete operations selecting protected Git metadata and hooks.",example:"find .git -delete",intent:"hard_stop",catastrophic:!0},{id:"find.exec-rm-recursive-force",category:"Filesystem",label:"find exec rm -rf",description:"Blocks find -exec rm -rf operations.",example:"find . -exec rm -rf {} +",intent:"scope_down"},{id:"rsync.delete",category:"Filesystem",label:"rsync delete",description:"Blocks rsync delete modes whose destination is outside the cwd, a temp root, or a variable.",example:'rsync -a --delete "$SRC/" "$DST/"',intent:"scope_down"},{id:"dd.device-write",category:"Filesystem",label:"dd device write",description:"Blocks dd writing to a /dev device other than /dev/null, /dev/zero, or /dev/full.",example:"dd if=/dev/zero of=/dev/sda",intent:"manual_only"},{id:"mkfs.device",category:"Filesystem",label:"Filesystem format on a device",description:"Blocks mkfs, mke2fs, and newfs formatting a /dev device.",example:"mkfs.ext4 /dev/sda1",intent:"manual_only"},{id:"disk.erase",category:"Filesystem",label:"Disk erase or repartition",description:"Blocks diskutil erase and partition verbs, wipefs -a/-o, sgdisk writes, and parted label or partition edits on a /dev device.",example:"diskutil eraseDisk APFS Untitled disk4",intent:"manual_only"},{id:"shred.target",category:"Filesystem",label:"shred target",description:"Blocks shred against any target, including shred --help and shred --version.",example:"shred -u secret.txt",intent:"use_alternative"},{id:"redirect.block-device",category:"Filesystem",label:"Redirect onto a disk device",description:"Blocks output redirects whose literal target is a disk device path under /dev.",example:"cat disk.img > /dev/sda",intent:"manual_only"},{id:"network.cloud-metadata",category:"Network",label:"Cloud metadata endpoint",description:"Blocks HTTP clients, raw socket tools, and code interpreters naming a cloud metadata host (169.254.169.254, fd00:ec2::254, 169.254.170.2, 169.254.170.23, fd00:ec2::23, metadata.google.internal, metadata.goog, 100.100.100.200).",example:"curl http://169.254.169.254/latest/meta-data/iam/security-credentials/",intent:"manual_only"},{id:"network.upload-remote",category:"Network",label:"Data upload to a remote host",description:"Blocks curl and wget requests that send a body or upload a file in strict mode unless every URL is loopback (localhost, *.localhost, 127.0.0.0/8, 0.0.0.0, [::1]).",example:"curl -T backup.tar https://uploads.example.com/",intent:"manual_only",activationCapability:"fail_closed"},{id:"unshare.user-namespace",category:"Execution",label:"unshare user namespace",description:"Blocks unshare creating a user namespace: -U/--user, -r/--map-root-user, -c/--map-current-user, --map-user(s), --map-group(s), or --map-auto.",example:"unshare -r id",intent:"manual_only"},{id:"interpreter.dangerous-command",category:"Execution",label:"Interpreter dangerous command",description:"Blocks interpreter one-liners containing dangerous commands.",example:`python -c "import os; os.system('rm -rf /')"`,intent:"use_alternative"},{id:"interpreter.one-liner-paranoid",category:"Execution",label:"Interpreter one-liner paranoid mode",description:"Blocks interpreter one-liners when paranoid interpreters is enabled.",example:'python -c "print(1)"',intent:"use_alternative",activationCapability:"paranoid_interpreters"},{id:"awk.system-dynamic",category:"Execution",label:"Awk dynamic system call",description:"Blocks awk system calls that cannot be safely analyzed.",example:"awk '{ system($0) }'",intent:"stop_and_explain"},{id:"xargs.rm-recursive-force-dynamic",category:"Execution",label:"xargs dynamic rm -rf",description:"Blocks xargs rm -rf with dynamic input.",example:"printf / | xargs rm -rf",intent:"scope_down"},{id:"xargs.shell-dynamic",category:"Execution",label:"xargs dynamic shell",description:"Blocks xargs shell execution with dynamic input.",example:"xargs r$(printf m) -rf",intent:"scope_down"},{id:"parallel.rm-recursive-force-dynamic",category:"Execution",label:"parallel dynamic rm -rf",description:"Blocks parallel rm -rf with dynamic input.",example:"printf / | parallel rm -rf",intent:"scope_down"},{id:"parallel.shell-dynamic",category:"Execution",label:"parallel dynamic shell",description:"Blocks parallel shell execution with dynamic input.",example:"parallel r$(printf m) -rf ::: child",intent:"scope_down"},{id:"parallel.command-stream-dynamic",category:"Execution",label:"parallel dynamic command stream",description:"Blocks parallel command streams from dynamic input.",example:"parallel --dry-run",intent:"scope_down"},{id:"shell.dynamic-structure",category:"Execution",label:"Dynamic command structure",description:"Blocks guarded subcommands and options assembled from substitution output in strict mode.",example:"git reset $(printf --hard)",intent:"stop_and_explain",activationCapability:"fail_closed"},{id:"shell.dynamic-executable",category:"Execution",label:"Dynamic executable name",description:"Blocks executable names assembled from command substitution output in strict mode.",example:"$(printf r)m -rf /",intent:"manual_only",activationCapability:"fail_closed"},{id:"raw-text.dangerous-command",category:"Execution",label:"Raw text dangerous command",description:"Blocks dangerous commands detected in raw command text.",example:"git reset --hard 'unterminated",intent:"stop_and_explain"}],Zs=new Set(Ud.map((e)=>e.id)),Io=Ud,gC=new Map(Io.map((e)=>[e.id,e.intent]));function b(e,t){return{id:e,reason:t,intent:gC.get(e)??"manual_only"}}var Xs=[{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"}],ko={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},hC=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],yC=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],Qs=[{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"]},...yC.flatMap((e)=>hC.map((t)=>({id:["secret.home",e.idSlug,t.slice(1)].join("."),category:"Home path",label:[e.label,t].join(""),description:["Blocks home ",e.label,t," credential backup files."].join(""),suffixParts:[...e.directoryParts,[e.basename,t].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 Oo=[{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.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","<project>/.codex/config.toml"]},{id:"secret.cli.gemini",category:"Coding CLI credential",label:"Gemini CLI credentials",paths:["~/.gemini/oauth_creds.json","~/.gemini/mcp-oauth-tokens.json","~/.gemini/a2a-oauth-tokens.json","~/.gemini/gemini-credentials.json"]},{id:"secret.cli.gemini.config",category:"Coding CLI config",label:"Gemini CLI config",paths:["~/.gemini/settings.json","~/.gemini/google_accounts.json","<project>/.gemini/settings.json","/Library/Application Support/GeminiCli/settings.json","/etc/gemini-cli/settings.json"]},{id:"secret.cli.copilot-cli",category:"Coding CLI credential",label:"GitHub Copilot CLI credentials",paths:["~/.copilot/config.json","~/.copilot/mcp-oauth-config","~/.copilot/mcp-secrets"]},{id:"secret.cli.copilot-cli.config",category:"Coding CLI config",label:"GitHub Copilot CLI config",paths:["~/.copilot/mcp-config.json"]},{id:"secret.cli.kimi-code",category:"Coding CLI credential",label:"Kimi Code credentials",paths:["~/.kimi-code/server.token","~/.kimi-code/credentials","~/.kimi/credentials","~/.kimi/mcp-oauth"]},{id:"secret.cli.kimi-code.config",category:"Coding CLI config",label:"Kimi Code config",paths:["~/.kimi-code/config.toml","~/.kimi-code/mcp.json","~/.kimi/config.toml","~/.kimi/config.json","~/.kimi/config.json.bak","~/.kimi/mcp.json","<project>/.kimi-code/mcp.json"]},{id:"secret.cli.opencode",category:"Coding CLI credential",label:"OpenCode credentials",paths:["~/.local/share/opencode/auth.json","~/.local/share/opencode/mcp-auth.json","~/.local/share/opencode/opencode.db"]},{id:"secret.cli.opencode.config",category:"Coding CLI config",label:"OpenCode config",paths:["~/.config/opencode/opencode.json","~/.config/opencode/opencode.jsonc","~/.config/opencode/config.json","/Library/Application Support/opencode/opencode.json","/etc/opencode/opencode.json","<project>/opencode.json","<project>/opencode.jsonc"]},{id:"secret.cli.pi",category:"Coding CLI credential",label:"Pi credentials",paths:["~/.pi/agent/auth.json"]},{id:"secret.cli.pi.config",category:"Coding CLI config",label:"Pi config",paths:["~/.pi/agent/models.json"]},{id:"secret.cli.amp",category:"Coding CLI credential",label:"Amp Code credentials",paths:["~/.local/share/amp/secrets.json","~/.amp/oauth"]},{id:"secret.cli.amp.config",category:"Coding CLI config",label:"Amp Code config",paths:["~/.config/amp/settings.json","~/.config/amp/settings.jsonc","<project>/.amp/settings.json","<project>/.amp/settings.jsonc"]},{id:"secret.cli.cursor",category:"Coding CLI credential",label:"Cursor CLI credentials",paths:["~/.cursor/auth.json","~/.config/cursor/auth.json","~/.cursor/projects/<name>/mcp-auth.json"]},{id:"secret.cli.cursor.config",category:"Coding CLI config",label:"Cursor CLI config",paths:["~/.cursor/mcp.json","<project>/.cursor/mcp.json"]},{id:"secret.cli.grok-build",category:"Coding CLI credential",label:"Grok Build credentials",paths:["~/.grok/auth.json","~/.grok/mcp_credentials.json"]},{id:"secret.cli.grok-build.config",category:"Coding CLI config",label:"Grok Build config",paths:["~/.grok/config.toml","~/.grok/managed_config.toml","~/.grok/requirements.toml","<project>/.grok/config.toml","/etc/grok/managed_config.toml","/etc/grok/requirements.toml"]},{id:"secret.cli.droid",category:"Coding CLI credential",label:"Factory Droid credentials",paths:["~/.factory/auth.encrypted","~/.factory/auth.v2.file","~/.factory/auth.v2.key","~/.factory/auth.v2.loginkeychain"]},{id:"secret.cli.droid.config",category:"Coding CLI config",label:"Factory Droid config",paths:["~/.factory/settings.json","~/.factory/hooks.json","~/.factory/mcp.json","<project>/.factory/mcp.json"]},{id:"secret.cli.devin",category:"Coding CLI credential",label:"Devin CLI credentials",paths:["~/.local/share/devin/credentials.toml","~/.local/share/devin/mcp/oauth"]},{id:"secret.cli.devin.config",category:"Coding CLI config",label:"Devin CLI config",paths:["~/.config/devin/config.json"]}],Hd=[{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"}],SC=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],Js=Hd.map((e)=>({id:`secret.variant.${e.slug}.separator`,category:"Variant",label:`${e.label}-* / ${e.label}_*`,description:`Blocks ${e.label} variants with dash or underscore suffixes.`,prefix:e.prefix})),ea=Hd.flatMap((e)=>SC.map((t)=>({id:`secret.variant.${e.slug}.${t.slice(1)}`,category:"Variant",label:`${e.label}${t}`,description:`Blocks ${e.label}${t} private credential variants.`,prefix:e.prefix,suffix:t}))),Er={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)$/},ta=["agilekeychain","asc","bek","cscfg","fve","gnucash","jks","keychain","kwallet","mdf","ovpn","p12","pcap","pem","pfx","pkcs12","psafe3","rdp","sdf","tblk","tpm"].map((e)=>({id:`secret.ext.${e}`,category:"Extension",label:`.${e}`,description:`Blocks files with the .${e} extension.`,extension:e})),na=[{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?$/}],CC=[...Xs,ko,...Qs,...Js,...ea,Er,...ta,...na,...Oo].map((e)=>({id:e.id,category:e.category,label:e.label,...e.category==="Coding CLI config"?{defaultOff:!0}:{},..."paths"in e?{paths:e.paths}:{description:e.description}})),Do=new Set(Oo.flatMap((e)=>e.category==="Coding CLI config"?[e.id]:[])),ra=new Set(CC.map((e)=>e.id));import{isAbsolute as oa,join as bC,normalize as vC,sep as Mo}from"path";var No=process.platform==="win32",jd=/[*?]/;function ia(e){let t=e.trim(),n=/^(.*)\/\*\*\/([^/*?\\]+)$/.exec(No?t.replaceAll("\\","/"):t);if(!n)return null;let r=n[1]??"",o=n[2]??"";if(jd.test(r)||o==="."||o==="..")return null;return{root:r||"/",name:o}}function Rr(e,t){if(e==="~")return t;if(e.startsWith("~/"))return`${t}${e.slice(1)}`;return e}function sa(e,t){if(typeof e!=="string"||e.trim()==="")return"must be a non-empty path string";let n=Rr(e.trim(),t);if(!oa(n))return"must be an absolute path or start with ~/";return wr(n,t)}function aa(e,t){let n=Vd(e,t);if(n===null)return"must be a non-empty path string";if(!oa(n))return null;if(wr(n,t)===null)return null;return"cannot be the home directory or a path above it (this would block every command the agent runs)"}var EC="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",RC="cannot cover the guard's own configuration";function Vd(e,t){if(typeof e!=="string"||e.trim()==="")return null;let n=e.trim(),r=No?n.replaceAll("\\","/"):n;return Rr(r.replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),t)}function la(e,t){let n=Vd(e,t);if(n===null)return"must be a non-empty path string";let r=ia(n)?.root??n;if(jd.test(r))return"supports only a folder followed by **/ and an exact file name, such as ~/code/**/.env.local";if(!oa(r))return null;if(wr(r,t)!==null)return EC;return wC(r,t)?RC:null}function wC(e,t){let n=Lo(e),r=Lo(bC(t,".cc-safety-net"));return n===r||n.startsWith(`${r}${Mo}`)}function wr(e,t){let n=Lo(e),r=Lo(t);if(n===r)return"cannot be the home directory";let o=n.endsWith(Mo)?n:`${n}${Mo}`;if(r.startsWith(o))return"cannot contain the home directory";return null}function Lo(e){let t=vC(e);if(No)t=t.replace(/\//g,"\\").toLowerCase();if(t.length>(No?3:1)&&t.endsWith(Mo))t=t.slice(0,-1);return t}var qd=30,Wo=1,Fo=365;function Kd(e){if(typeof e!=="number"||!Number.isInteger(e))return 30;if(e<1)return 1;return e>365?365:e}var Yd=new Set(Io.filter((e)=>e.catastrophic).map((e)=>e.id));function O(e,t){if(!e)return null;if(Yd.has(e.id))return e;if(t?.destructiveCommandProtectionEnabled===!1)return null;let n=t?.effectiveDestructiveCommandRules[e.id];return n&&!n.enabled?null:e}function ae(e,t,n){if(Yd.has(t))return!0;if(e?.destructiveCommandProtectionEnabled===!1)return!1;return e?.effectiveDestructiveCommandRules[t]?.enabled??n}function Zd(e,t){return Object.freeze(Object.fromEntries(Io.map((n)=>{let r=n.activationCapability?t[n.activationCapability]:void 0,o=r?.enabled??!0,i=e.destructiveCommandRuleOverrides[n.id],s=n.catastrophic?{enabled:!0,inheritedEnabled:!0,changesInherited:!1,source:"catastrophic",...i?{override:i}:{}}:e.destructiveCommandProtectionEnabled?i?{enabled:i==="on",inheritedEnabled:o,changesInherited:i==="on"!==o,source:"rule_override",...n.activationCapability?{activationCapability:n.activationCapability}:{},override:i}:{enabled:o,inheritedEnabled:o,changesInherited:!1,source:r?.source??"built_in_default",...n.activationCapability?{activationCapability:n.activationCapability}:{}}:{enabled:!1,inheritedEnabled:o,changesInherited:!1,source:"master_disabled",...n.activationCapability?{activationCapability:n.activationCapability}:{},...i?{override:i}:{}};return[n.id,Object.freeze(s)]})))}function Xd(e,t){return Object.freeze({...e,effectiveDestructiveCommandRules:Zd(e,t)})}var Qd={standard:0,strict:1,paranoid:2};function tu(e,t,n=!1,r=e.safety.level){let o=_C(e,t,r),i=new Set(n?o.map((d)=>d.field):[]),s=(d,u)=>i.has(d)?void 0:u,a=(d,u)=>Object.fromEntries(Object.entries(u??{}).filter(([f])=>!i.has(`${d}.${f}`))),l=(d,u)=>u?.filter((f)=>!i.has(`${d}.${f}`));return{policy:{version:1,safety:{level:s("safety.level",t.safety?.level)??e.safety.level,overrides:{...e.safety.overrides,...a("safety.overrides",t.safety?.overrides)}},workflow:{worktree_mode:s("workflow.worktree_mode",t.workflow?.worktree_mode)??e.workflow.worktree_mode},destructive_command_protection:{enabled:s("destructive_command_protection.enabled",t.destructive_command_protection?.enabled)??e.destructive_command_protection.enabled,overrides:{...e.destructive_command_protection.overrides,...a("destructive_command_protection.overrides",t.destructive_command_protection?.overrides)},allow_paths:ca(e.destructive_command_protection.allow_paths,l("destructive_command_protection.allow_paths",t.destructive_command_protection?.allow_paths))},secret_protection:{enabled:s("secret_protection.enabled",t.secret_protection?.enabled)??e.secret_protection.enabled,overrides:{...e.secret_protection.overrides,...a("secret_protection.overrides",t.secret_protection?.overrides)},deny_paths:ca(e.secret_protection.deny_paths,t.secret_protection?.deny_paths),allow_paths:ca(e.secret_protection.allow_paths,l("secret_protection.allow_paths",t.secret_protection?.allow_paths))},audit:e.audit},weakenings:o.map((d)=>d.message)}}function ca(e,t){return[...new Set([...e,...t??[]])]}function _C(e,t,n){let r=t.safety?.level,o=yo[n];return[...r&&Qd[r]<Qd[e.safety.level]?[{field:"safety.level",message:`project policy lowers level: ${e.safety.level} -> ${r}`}]:[],...xn.flatMap((i)=>t.safety?.overrides?.[i]===!1&&(e.safety.overrides[i]??o[i])?[{field:`safety.overrides.${i}`,message:`project policy disables ${i}`}]:[]),...t.workflow?.worktree_mode===!0&&!e.workflow.worktree_mode?[{field:"workflow.worktree_mode",message:"project policy enables worktree mode relaxations"}]:[],...t.destructive_command_protection?.enabled===!1&&e.destructive_command_protection.enabled?[{field:"destructive_command_protection.enabled",message:"project policy disables destructive command protection"}]:[],...t.secret_protection?.enabled===!1&&e.secret_protection.enabled?[{field:"secret_protection.enabled",message:"project policy disables secret protection"}]:[],...Jd("destructive_command_protection.overrides",t.destructive_command_protection?.overrides,(i)=>e.destructive_command_protection.enabled&&e.destructive_command_protection.overrides[i]!=="off"),...Jd("secret_protection.overrides",t.secret_protection?.overrides,(i)=>e.secret_protection.enabled&&(e.secret_protection.overrides[i]==="on"?!0:e.secret_protection.overrides[i]!=="off"&&!Do.has(i))),...e.destructive_command_protection.enabled?eu(e.destructive_command_protection.allow_paths,t.destructive_command_protection?.allow_paths).map((i)=>({field:`destructive_command_protection.allow_paths.${i}`,message:`project policy adds destructive allow path: ${i}`})):[],...e.secret_protection.enabled?eu(e.secret_protection.allow_paths,t.secret_protection?.allow_paths).map((i)=>({field:`secret_protection.allow_paths.${i}`,message:`project policy adds secret allow path: ${i}`})):[]]}function Jd(e,t,n){return Object.entries(t??{}).flatMap(([r,o])=>o==="off"&&n(r)?[{field:`${e}.${r}`,message:`project policy disables rule ${r}`}]:[])}function eu(e,t){return(t??[]).filter((n)=>!e.includes(n))}var ua=new Set(["standard","strict","paranoid"]),ou={version:1,safety:{level:"standard",overrides:{}},workflow:{worktree_mode:!1},destructive_command_protection:{enabled:!0,overrides:{},allow_paths:[]},secret_protection:{enabled:!0,overrides:{},deny_paths:[],allow_paths:[]},audit:{retention_days:qd}};function iu(e,t){let n=WC(Vt(e,t),e.home),r=Sd(e,t)?{exists:!1,policy:Yt(),errors:[]}:zo(An(t.cwd),e.home),o=TC(r.parsed,e.home),i=dt(J.projectTightenOnly,e.env),s=n.gui??ou,a=Object.keys(o.policy).length>0?tu(s,o.policy,i,rd(s.safety.level,e.env)):void 0,l=[...n.errors,...r.errors,...o.diagnostics],c=(n.fallback==="defaults"&&a?"salvaged":n.fallback)??(n.gui?void 0:r.fallback)??(l.length>0?"salvaged":void 0),d=o.policy.safety?.level&&a?.policy.safety.level===o.policy.safety.level?"project":n.levelPresent?"user":"default";return{...a?_r(a.policy):n.policy,errors:l,...c?{fallback:c}:{},...r.exists?{policyScopes:{levelScope:d,weakenings:a?.weakenings??[],weakeningsIgnored:i}}:{}}}var PC="project policy audit settings are ignored; audit is user scope only";function TC(e,t){if(!Me(e))return{policy:{},diagnostics:[]};let n=Me(e.safety)?e.safety:{},r=Me(e.workflow)?e.workflow:{},o=Me(e.destructive_command_protection)?e.destructive_command_protection:{},i=Me(e.secret_protection)?e.secret_protection:{},s={...ua.has(n.level)?{level:n.level}:{},...Me(n.overrides)?nu({overrides:su(n.overrides,xn,["safety","overrides"],Kt)}):{}},a={...typeof o.enabled==="boolean"?{enabled:o.enabled}:{},...o.overrides!==void 0?{overrides:Go(o.overrides,Zs,lu,Kt)}:{},...o.allow_paths!==void 0?{allow_paths:Tn(o.allow_paths,sa,t,["destructive_command_protection","allow_paths"],Kt)}:{}},l={...typeof i.enabled==="boolean"?{enabled:i.enabled}:{},...i.overrides!==void 0?{overrides:Go(i.overrides,ra,cu,Kt)}:{},...i.deny_paths!==void 0?{deny_paths:Tn(i.deny_paths,aa,t,["secret_protection","deny_paths"],Kt)}:{},...i.allow_paths!==void 0?{allow_paths:Tn(i.allow_paths,la,t,["secret_protection","allow_paths"],Kt)}:{}};return{policy:nu({safety:s,workflow:typeof r.worktree_mode==="boolean"?{worktree_mode:r.worktree_mode}:{},destructive_command_protection:a,secret_protection:l}),diagnostics:e.audit===void 0?[]:[PC]}}function su(e,t,n,r){return Object.fromEntries(t.flatMap((o)=>{let i=e[o];if(typeof i==="boolean")return[[o,i]];if(i!==void 0)r(T([...n,o],ma));return[]}))}function nu(e){return Object.fromEntries(Object.entries(e).flatMap((t)=>Object.keys(t[1]).length>0?[t]:[]))}var Kt=()=>{return},ma="must be a boolean",fa="must be an object if provided",au=`must be an integer between ${Wo} and ${Fo}`,lu={path:["destructive_command_protection","overrides"],label:"destructive command"},cu={path:["secret_protection","overrides"],label:"secret protection"},IC=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function kC(e,t){let n=[];return{policy:du(e,t,(o)=>{n.push(o)}),issues:n}}function OC(e,t){return du(e,t,Kt)}function du(e,t,n){if(!Me(e))return n(T([],"Config must be an object")),Yt();if(e.version!==1)n(T(["version"],"must be 1"));let r=Pn(e.safety,["safety"],["level","overrides"],n),o=Pn(r.overrides,["safety","overrides"],xn,n),i=Pn(e.workflow,["workflow"],["worktree_mode"],n),s=Pn(e.destructive_command_protection,["destructive_command_protection"],["enabled","overrides","allow_paths"],n),a=Pn(e.secret_protection,["secret_protection"],["enabled","overrides","deny_paths","allow_paths"],n),l=Pn(e.audit,["audit"],["retention_days"],n);return uu(e,IC,[],n),{version:1,safety:{level:DC(r.level,n),overrides:su(o,xn,["safety","overrides"],n)},workflow:{worktree_mode:da(i.worktree_mode,["workflow","worktree_mode"],!1,n)},destructive_command_protection:{enabled:da(s.enabled,["destructive_command_protection","enabled"],!0,n),overrides:Go(s.overrides,Zs,lu,n),allow_paths:Tn(s.allow_paths,sa,t,["destructive_command_protection","allow_paths"],n)},secret_protection:{enabled:da(a.enabled,["secret_protection","enabled"],!0,n),overrides:Go(a.overrides,ra,cu,n),deny_paths:Tn(a.deny_paths,aa,t,["secret_protection","deny_paths"],n),allow_paths:Tn(a.allow_paths,la,t,["secret_protection","allow_paths"],n)},audit:{retention_days:MC(l.retention_days,n)}}}function Pn(e,t,n,r){if(e===void 0)return{};if(!Me(e))return r(T(t,fa)),{};return uu(e,n,t,r),e}function uu(e,t,n,r){for(let o of Object.keys(e).filter((i)=>!t.includes(i)))r({path:n,message:o,kind:"unknownKeys"})}function DC(e,t){if(e===void 0)return"standard";if(ua.has(e))return e;return t(T(["safety","level"],'must be "standard", "strict", or "paranoid"')),"standard"}function da(e,t,n,r){if(typeof e==="boolean")return e;if(e!==void 0)r(T(t,ma));return n}function MC(e,t){if(!(e===void 0||typeof e==="number"&&Number.isInteger(e)&&e>=Wo&&e<=Fo))t(T(["audit","retention_days"],au));return Kd(e)}function Go(e,t,n,r){if(e===void 0)return{};if(!Me(e))return r(T(n.path,fa)),{};return Object.fromEntries(Object.entries(e).flatMap(([o,i])=>{if(!t.has(o))return r({path:[...n.path,o],message:`unknown ${n.label} rule id "${o}"`,kind:"key"}),[];if(i==="on"||i==="off")return[[o,i]];return r(T([...n.path,o],'must be "on" or "off"')),[]}))}function Tn(e,t,n,r,o){if(e===void 0)return[];if(!Array.isArray(e))return o(T(r,"must be an array of paths")),[];return e.flatMap((i,s)=>{let a=t(i,n);if(a===null)return[i];return o(typeof i==="string"?se([...r,s],a):T([...r,s],a)),[]})}function Me(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function Yt(){return structuredClone(ou)}function zo(e,t){if(!xC(e))return{exists:!1,policy:Yt(),errors:[]};try{let n=AC(e,"utf-8");if(!n.trim())return{exists:!0,policy:Yt(),errors:[`${e}: Config file is empty`],fallback:"defaults"};let r=JSON.parse(n),o=kC(r,t);if(o.issues.length===0)return{exists:!0,parsed:r,policy:o.policy,errors:[]};return{exists:!0,parsed:r,policy:o.policy,errors:o.issues.map((i)=>`${e}: ${LC(i)}`),fallback:Me(r)?"salvaged":"defaults"}}catch(n){let r=n instanceof Error?n.message:String(n);return{exists:!0,policy:Yt(),errors:[`${e}: ${n instanceof SyntaxError?"Invalid JSON":r}`],fallback:"defaults"}}}var NC=new Map([["Config must be an object","not a JSON object"],["must be 1","not 1"],[fa,"not an object"],['must be "standard", "strict", or "paranoid"',"not one of standard, strict, paranoid"],[ma,"not a boolean"],['must be "on" or "off"','not "on" or "off"'],["must be an array of paths","not an array"],[au,`not an integer between ${Wo} and ${Fo}`]]);function LC(e){let t=Ks(e.path);if(e.kind==="unknownKeys")return`${t===""?"":`${t}.`}${e.message}: unknown field`;if(e.kind==="key")return`${t}: unknown rule id`;let n=NC.get(e.message)??e.message;return t===""?n:`${t}: ${n}`}function WC(e,t){let n=zo(e,t);if(!n.exists){let r=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!Me(r))return{policy:_r(Yt()),errors:[]};let o=OC(r,t);return{policy:_r(o),gui:o,errors:[],levelPresent:ru(r)}}if(n.parsed===void 0)return{policy:_r(Yt()),errors:n.errors,...n.fallback?{fallback:n.fallback}:{}};return{policy:_r(n.policy),gui:n.policy,errors:n.errors,...n.fallback?{fallback:n.fallback}:{},levelPresent:ru(n.parsed)}}function ru(e){let t=Me(e)&&Me(e.safety)?e.safety:{};return ua.has(t.level)}function FC(e){let t=Object.entries(e),n=new Set(t.flatMap(([r,o])=>o==="on"?[r]:[]));return[...new Set([...[...Do].filter((r)=>!n.has(r)),...t.flatMap(([r,o])=>o==="off"?[r]:[])])]}function _r(e){return{safety:GC(e.safety),worktreeMode:e.workflow.worktree_mode,destructiveCommandProtectionEnabled:e.destructive_command_protection.enabled,destructiveCommandRuleOverrides:e.destructive_command_protection.overrides,destructiveCommandAllowPaths:e.destructive_command_protection.allow_paths,secretProtection:{enabled:e.secret_protection.enabled,disabledRules:FC(e.secret_protection.overrides),denyPaths:e.secret_protection.deny_paths,allowPaths:e.secret_protection.allow_paths}}}function GC(e){let t={...e.overrides.fail_closed!==void 0?{failClosed:e.overrides.fail_closed}:{},...e.overrides.paranoid_rm!==void 0?{paranoidRm:e.overrides.paranoid_rm}:{},...e.overrides.paranoid_interpreters!==void 0?{paranoidInterpreters:e.overrides.paranoid_interpreters}:{}};return{level:e.level,...Object.keys(t).length>0?{overrides:t}:{}}}function mu(e,t){let n=Bd(e,t),r=iu(e,t),o={rules:n.rules,transparentWrappers:n.transparent_wrappers,commandTools:n.command_tools,safety:r.safety,worktreeMode:r.worktreeMode,destructiveCommandProtectionEnabled:r.destructiveCommandProtectionEnabled,destructiveCommandRuleOverrides:r.destructiveCommandRuleOverrides,destructiveCommandAllowPaths:r.destructiveCommandAllowPaths,secretProtection:{enabled:r.secretProtection.enabled??!0,disabledRules:r.secretProtection.disabledRules??[],denyPaths:r.secretProtection.denyPaths,allowPaths:r.secretProtection.allowPaths??[]}},i={...n.userConfig?.overrides,...n.projectConfig?.overrides},s=Object.freeze(Object.fromEntries(o.rules.map((a)=>{let l=n.rulebooks.find((d)=>d.rules.includes(a.name)),c=i[a.name];return[a.name,Object.freeze({id:a.name,...l?{rulebook:Object.freeze({name:l.name,version:l.version}),...UC(l.spec)?{source:l.spec}:{}}:{},...c&&typeof c==="object"?{override:Object.freeze({type:"reason",reason:c.reason})}:{}})]})));return HC(o,zC(n,r),s,r.policyScopes)}function zC(e,t){let n=BC(t);if(e.errors.length===0&&e.warnings.length===0&&!n)return;return{diagnostics:[...e.errors,...e.warnings,...t.errors],reason:jC(e.errors.length>0?$C(e.errors):void 0,e.warnings.length>0?ga(e.warnings.join("; ")):void 0,n)}}function $C(e){return`${ga(e.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function BC(e){if(e.errors.length===0)return;let t=e.fallback==="salvaged"?"the salvaged policy with protective defaults":"built-in protective defaults";return`invalid policy config: ${e.errors.join("; ")}. Enforcing ${t}; the invalid values are not active. Fix the policy file manually`}function UC(e){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(e)}function HC(e,t,n=Object.freeze({}),r){let o=pa(structuredClone(e)),i=r?{policyScopes:pa(structuredClone(r))}:{};if(!t)return Object.freeze({state:"ready",policy:o,diagnostics:Object.freeze([]),ruleMetadata:n,...i});return Object.freeze({state:"degraded",policy:o,diagnostics:Object.freeze([...t.diagnostics]),reason:t.reason,ruleMetadata:n,...i})}function pa(e){if(typeof e!=="object"||e===null)return e;for(let t of Object.values(e))pa(t);return Object.freeze(e)}function jC(...e){return ga(e.filter((t)=>!!t).join("; "))}function ga(e){return/[.!?]$/.test(e)?e:`${e}.`}function $o(e){let t=e.effectiveCapabilities,n=t.fail_closed.enabled,r=t.paranoid_rm.enabled,o=t.paranoid_interpreters.enabled;return{policy:Xd(e.policySnapshot.policy,t),effectiveCapabilities:t,effectiveLevel:ws({failClosed:n,paranoidRm:r,paranoidInterpreters:o}),strict:n,paranoidRm:r,paranoidInterpreters:o,worktreeMode:e.worktreeMode??!1}}import{dirname as AP,isAbsolute as PP,join as yg,parse as TP,resolve as IP,sep as kP}from"path";function xr(e,t){if(e!=="powershell")return t[0]?.provenance==="command-substitution";let n=t[0]?.text==="&"||t[0]?.text==="."?1:0,r=t[n];return r!==void 0&&(r.provenance!=="literal"||n===0&&qC(r))}var VC=/^@(['"])[ \t]*(?:\r\n|[\r\n])/;function In(e,t){let n=VC.exec(e.slice(t)),r=n?.[1];return n&&r?{quote:r,bodyStart:t+n[0].length}:null}function qC(e){return In(e.raw,0)!==null}var KC=/^[A-Za-z_][A-Za-z0-9_]*=/;function Bo(e,t){return e?.provenance==="literal"&&!e.quoted&&e.raw===t&&e.text===t}function Ar(e){let t=Bo(e.words[0],"time")?1:0,n=t===1&&Bo(e.words[t],"-p")?t+1:t,r=t===1&&Bo(e.words[n],"--")?n+1:n,o=Bo(e.words[r],"!")?r+1:r,i=e.words.slice(o).find((s)=>!KC.test(s.text));return i?.provenance==="literal"?i.text:void 0}var Tt=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function Uo(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function Ho(e,t,n){e.push(n),t.reset()}function jo(e){let t=[];return{parts:t,push:(n,r,o)=>{if(r<=n)return;t.push({raw:e.slice(n,r),span:{start:n,end:r},provenance:o})}}}function ha(e){let t=e.parts??[{raw:e.raw,span:e.span,provenance:e.provenance}];return{kind:"word",...e,parts:t}}function kn(e,t,n,r,o,i,s){return ha({text:r,raw:e.slice(t,n),span:{start:t,end:n},provenance:o,quoted:i,...s?{parts:s}:{}})}function ya(e,t,n){if(t>=n||pu(e[t]??""))return null;let r="",o=!1,i=!1,s=t;while(s<n&&!pu(e[s]??"")){let a=e[s]??"";if(a==="'"){o=!0;let l=fu(e,s+1,n,"'");r+=l.text,i||=!l.closed,s=l.next;continue}if(a==='"'){o=!0;let l=fu(e,s+1,n,'"');r+=l.text,i||=!l.closed,s=l.next;continue}if(a==="\\"){o=!0;let l=e[s+1];if(!l||l===`
8
+ `||s==="\r")t+=s,r=!1,n.escaped=!1;continue}if(s==="#"&&!n.inSingle&&!n.inDouble&&o){r=!0;continue}if(t+=s,!n.inSingle&&!n.inDouble&&!n.escaped)o=/[\s;&|()<>]/.test(s);vr(s,n)}return t}var Bs=new Set(["rm","find","rsync","xargs","parallel"]),PS=new Set(["git","busybox",...Bs,...Q,...vd,...Fe]),TS=new Set(["python","node","ruby","perl"]);function _d(e){let t=N(e);return PS.has(t)||De(t)}function De(e){return TS.has(IS(e))}function IS(e){let t=k(e).toLowerCase();return wo.test(t)?"python":t}function js(e){try{let t=vo(kS(e));if(t===null)return{config:null,errors:[]};if(!t.trim())return{config:null,errors:["Config file is empty"]};let n=JSON.parse(t),r=NS(n);if(r.errors.length>0)return{config:null,errors:r.errors};return{config:{version:1,rules:n.rules??[],overrides:n.overrides??{},transparent_wrappers:n.transparent_wrappers??[],...n.command_tools?{command_tools:n.command_tools}:{}},errors:[]}}catch(t){if(t instanceof he)return{config:null,errors:[t.message]};let n=t instanceof Error?t.message:String(t);return{config:null,errors:[t instanceof SyntaxError?"Invalid JSON":n]}}}function kS(e){return typeof e==="string"?ld(e):e}var T=(e,t)=>({path:e,message:t,kind:"typed"}),se=(e,t)=>({path:e,message:t,kind:"custom"});function xd(e){let t=new Set;return e.flatMap((n,r)=>{let o=qt(n)?n.name:void 0;if(typeof o!=="string")return[];if(t.has(o.toLowerCase()))return[se(["rules",r,"name"],`duplicate rule name "${o}"`)];return t.add(o.toLowerCase()),[]})}var Vs=`must be one of ${Ws.join(", ")}`,OS=/^[^/]+\/[^/]+$/,DS=["version","rules","overrides","transparent_wrappers","command_tools"],MS=/^[^\s\p{Cc}]{1,256}$/u,Us="non-empty, at most 256 characters, no whitespace or control characters";function NS(e){let t=LS(e);return{errors:qs(VS(t,DS,(n)=>n.kind==="custom"),": "," "),sources:jS(e,t)}}function LS(e){if(!qt(e))return[T([],"Config must be an object")];let t=Array.isArray(e.rules)&&e.rules.length>Fs;return[...e.version===1?[]:[T(["version"],"must be 1")],...WS(e.rules,t),...zS(e.overrides),...BS(e.transparent_wrappers),...t?[]:GS(e.rules),...qt(e.overrides)?Object.keys(e.overrides).filter((n)=>!OS.test(n)).map((n)=>se(["overrides",n],"must use <rulebook-name>/<rule-name>")):[],...US(e.transparent_wrappers),...HS(e.command_tools)]}function WS(e,t){if(e===void 0)return[];if(!Array.isArray(e))return[T(["rules"],"must be an array of rulebook source strings"),...Ad(e,Fs)?[T(["rules"],Gs)]:[]];if(t)return[{path:["rules"],message:Gs,kind:"limit"}];return e.flatMap((n,r)=>{if(typeof n!=="string")return[T(["rules",r],"must be a rulebook source string"),...FS(n,1)?[T(["rules",r],"must be a non-empty rulebook source string")]:[]];return n===""?[T(["rules",r],"must be a non-empty rulebook source string")]:[]})}function Ad(e,t){let n=Pd(e);return n!==void 0&&!(n<=t)}function FS(e,t){let n=Pd(e);return n!==void 0&&!(n>=t)}function Pd(e){if(e===null||e===void 0)return;let t=e.length;return t===void 0?void 0:Number(t)}function GS(e){if(!Array.isArray(e))return[];let t=new Set;return e.flatMap((n,r)=>{if(typeof n!=="string"||n==="")return[];if(n.trim()==="")return[se(["rules",r],"must be a non-empty rulebook source string")];let o=pd(n);if(o)return[se(["rules",r],o)];if(t.has(n))return[se(["rules",r],`duplicate rulebook source "${n}"`)];return t.add(n),[]})}function zS(e){if(e===void 0)return[];if(!qt(e))return[T(["overrides"],"must be an object if provided")];return Object.keys(e).flatMap((t)=>{let n=e[t];if(n==="off")return[];if(!qt(n))return[T(["overrides",t],'must be "off" or an object')];return[...$S(n.reason,["overrides",t,"reason"]),...n.intent===void 0||Ys(n.intent)?[]:[T(["overrides",t,"intent"],Vs)]]})}function $S(e,t){if(typeof e!=="string")return[T(t,"required non-empty string"),...Ad(e,At)?[T(t,`must be at most ${At} characters`)]:[]];if(e==="")return[T(t,"required non-empty string")];return e.length>At?[T(t,`must be at most ${At} characters`)]:[]}function BS(e){if(e===void 0)return[];if(!Array.isArray(e))return[T(["transparent_wrappers"],"must be an array of command strings")];return e.flatMap((t,n)=>{if(typeof t!=="string")return[T(["transparent_wrappers",n],"must be a command string")];return xt.test(t)?[]:[T(["transparent_wrappers",n],"must match command pattern")]})}function US(e){if(!Array.isArray(e))return[];let t=new Set;return e.flatMap((n,r)=>{if(typeof n!=="string"||!xt.test(n))return[];if(t.has(n))return[se(["transparent_wrappers",r],`duplicate command "${n}"`)];if(_d(n))return[se(["transparent_wrappers",r],`reserved command "${n}" cannot be a wrapper`)];return t.add(n),[]})}function HS(e){if(e===void 0)return[];if(!Array.isArray(e))return[T(["command_tools"],"must be an array of tool names or {name, cwd} objects")];let t=new Set,n=(r,o)=>{if(t.has(r))return[se(["command_tools",o],`duplicate tool "${r}"`)];return t.add(r),[]};return e.flatMap((r,o)=>{if(typeof r==="string")return Hs(r)?n(r,o):[T(["command_tools",o],`must be a tool name: ${Us}`)];if(!qt(r))return[T(["command_tools",o],"must be a tool name or a {name, cwd} object")];let i=[...Hs(r.name)?[]:[T(["command_tools",o,"name"],`must be a tool name: ${Us}`)],...r.cwd===void 0||r.cwd===!1||Hs(r.cwd)?[]:[T(["command_tools",o,"cwd"],`must be an argument name or false: ${Us}`)]];return i.length>0?i:n(r.name,o)})}function Hs(e){return typeof e==="string"&&MS.test(e)}function jS(e,t){let n=qt(e)?e.rules:void 0;if(!Array.isArray(n))return new Set;if(t.some((o)=>o.path.length===1&&o.path[0]==="rules"))return new Set;let r=new Set(t.filter((o)=>o.path[0]==="rules"&&typeof o.path[1]==="number").map((o)=>o.path[1]));return new Set(n.filter((o,i)=>typeof o==="string"&&!r.has(i)))}function VS(e,t,n){let r=e.map((s)=>s.path[1]),o=[...new Set(r.filter((s)=>typeof s==="string"))],i=(s,a)=>[s.path.length===0?-1:t.indexOf(String(s.path[0])),typeof a==="number"?a:o.indexOf(String(a)),n(s)?0:1];return e.map((s,a)=>({issue:s,rank:i(s,r[a])})).sort((s,a)=>s.rank[0]-a.rank[0]||s.rank[1]-a.rank[1]||s.rank[2]-a.rank[2]).map((s)=>s.issue)}function qs(e,t,n){return[...new Set(e.map((r)=>{let o=Ks(r.path);if(r.kind==="unknownKeys")return`${o?`${o}.`:""}unknown field "${r.message}"`;if(r.kind==="key"||r.kind==="limit"||r.path.length===0)return r.message;return`${o}${r.path.length===1?n:t}${r.message}`}))]}function Ks(e){return e.map((t,n)=>{if(typeof t==="number")return`[${t}]`;return n===0?String(t):`.${String(t)}`}).join("")}function Ys(e){return Ws.includes(e)}function qt(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function Id(e){let t=YS(e);if(t.errors.length>0)throw Error(t.errors.join("; "));return e}var qS=`required non-empty string up to ${At} characters`,Td="must be a non-empty array of unique non-empty strings",KS="required non-empty array of non-empty strings";function YS(e){if(!Pt(e))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!wd(e))return{errors:[Ed],ruleNames:new Set};let t=[...e.rulebook_version===1||e.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],...qs(ZS(e,e.rulebook_version===2),": ",": ")];return{errors:t.length>Ue.maxValidationErrors?[...t.slice(0,Ue.maxValidationErrors),Rd]:t,ruleNames:new Set(kd(e).map((n)=>n.toLowerCase()))}}function kd(e){let t=Pt(e)?e.rules:void 0;return(Array.isArray(t)?t:[]).flatMap((n)=>{let r=Pt(n)?n.name:void 0;return typeof r==="string"?[r]:[]})}function ZS(e,t){return[...typeof e.name==="string"&&Ut.test(e.name)?[]:[T(["name"],"required string matching rule name pattern")],...typeof e.version==="string"&&e.version!==""?[]:[T(["version"],"required non-empty string")],...XS(e.allowed_commands),...QS(e.rules,t),...nC(e.tests),...rC(e),...oC(e)]}function XS(e){if(!Array.isArray(e))return[T(["allowed_commands"],"required array")];let t=new Set;return[...e.flatMap((n,r)=>typeof n==="string"&&xt.test(n)?[]:[T(["allowed_commands",r],"must match command pattern")]),...e.flatMap((n,r)=>{if(typeof n!=="string"||!xt.test(n))return[];if(t.has(n))return[se(["allowed_commands",r],`duplicate command "${n}"`)];return t.add(n),[]})]}function QS(e,t){if(!Array.isArray(e))return[T(["rules"],"required array")];return[...e.flatMap((n,r)=>{if(!Pt(n))return[T(["rules",r],"must be an object")];return t?eC(n,["rules",r]):JS(n,["rules",r])}),...xd(e)]}function JS(e,t){return[...Od(e.name,t),...Dd(e.command,t),...e.subcommand===void 0||typeof e.subcommand==="string"&&xt.test(e.subcommand)?[]:[T([...t,"subcommand"],"must match command pattern")],...Po(e.block_args,[...t,"block_args"],"required non-empty array",!1),...Md(e.reason,t),...Nd(e.intent,t)]}function eC(e,t){return[...Od(e.name,t),...Dd(e.command,t),...Md(e.reason,t),...Nd(e.intent,t),...tC(e.match,[...t,"match"]),...e.subcommand===void 0?[]:[T([...t,"subcommand"],"not supported in rulebook_version 2")],...e.block_args===void 0?[]:[T([...t,"block_args"],"not supported in rulebook_version 2")]]}function Od(e,t){if(typeof e!=="string")return[T([...t,"name"],"required string")];return Ut.test(e)?[]:[T([...t,"name"],"must match rule name pattern")]}function Dd(e,t){return typeof e==="string"&&xt.test(e)?[]:[T([...t,"command"],"required string matching command pattern")]}function Md(e,t){return typeof e==="string"&&e!==""&&e.length<=At?[]:[T([...t,"reason"],qS)]}function Nd(e,t){return e===void 0||Ys(e)?[]:[T([...t,"intent"],Vs)]}function tC(e,t){if(!Pt(e))return[T(t,"required object")];return[...Po(e.command_path,[...t,"command_path"],KS,!1),...e.any_args===void 0?[]:Po(e.any_args,[...t,"any_args"],Td,!0),...e.exclude_args===void 0?[]:Po(e.exclude_args,[...t,"exclude_args"],Td,!0)]}function Po(e,t,n,r){if(!Array.isArray(e))return[T(t,n)];let o=e.flatMap((i,s)=>{if(typeof i!=="string")return[T([...t,s],"must be a non-empty string")];return i===""?[se([...t,s],"must be a non-empty string")]:[]});if(e.some((i)=>typeof i!=="string"))return o;return[...o,...e.length===0?[se(t,n)]:[],...r&&new Set(e).size!==e.length?[se(t,"must not contain duplicate values")]:[]]}function nC(e){if(e===void 0)return[];if(!Array.isArray(e))return[T(["tests"],"must be an array if provided")];return e.flatMap((t,n)=>{if(!Pt(t))return[T(["tests",n],"must be an object")];return[...typeof t.command==="string"&&t.command.trim()!==""?[]:[T(["tests",n,"command"],"required non-empty string")],...t.expect==="blocked"||t.expect==="allowed"?[]:[T(["tests",n,"expect"],'must be "blocked" or "allowed"')],...t.rule===void 0||typeof t.rule==="string"?[]:[T(["tests",n,"rule"],"must be a string if provided")],...t.expect==="blocked"&&typeof t.rule!=="string"?[se(["tests",n,"rule"],"required string for blocked fixtures")]:[]]})}function rC(e){if(!Array.isArray(e.tests))return[];let t=new Set(kd(e));return[...new Set(e.tests.flatMap((n)=>Pt(n)&&n.expect==="blocked"&&typeof n.rule==="string"?[n.rule]:[]))].filter((n)=>!t.has(n)).map((n)=>se(["tests"],`blocked fixture references unknown rule "${n}"`))}function oC(e){if(!Array.isArray(e.allowed_commands)||!Array.isArray(e.rules))return[];let t=new Set(e.allowed_commands.filter((n)=>typeof n==="string"));return e.rules.flatMap((n,r)=>{let o=Pt(n)?n.command:void 0;if(typeof o!=="string"||t.has(o))return[];return[se(["rules",r,"command"],`"${o}" must be listed in allowed_commands`)]})}function Pt(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function Bd(e,t){let n=Cd(e,t),r;try{r=cd(n.userConfigTarget,n.projectConfigTarget)}catch(m){if(m instanceof he)return pC(n,m.message);throw m}let o=js(n.userConfigTarget),i=r?{config:null,errors:[]}:js(n.projectConfigTarget),s=zd(n.userConfigPath,o.errors),a=zd(n.projectConfigPath,i.errors),l=new Set,c=o.config?Ld(o.config,To(n.userConfigPath),"user",n.userScope,l):$d(),d=i.config?Ld(i.config,To(n.projectConfigPath),"project",n.projectScope,l):$d(),u=o.config?.overrides??{},f=i.config?.overrides??{};return{rules:[...Fd(c.rules,u),...Fd(d.rules,f)],transparent_wrappers:uC(o.config,i.config),command_tools:mC(o.config,i.config),rulebooks:[...c.rulebooks,...d.rulebooks],errors:[...s,...a,...c.errors,...d.errors],warnings:[...c.warnings,...d.warnings,...c.canValidateOverrides?Gd(u,c.knownRuleIds,n.userConfigPath):[],...c.canValidateOverrides?fC(f,c.knownRuleIds,n.projectConfigPath):[],...d.canValidateOverrides?Gd(f,d.knownRuleIds,n.projectConfigPath):[]],userConfig:o.config??void 0,projectConfig:i.config??void 0,...n}}function Ld(e,t,n,r=Bt(To(To(t)),n==="user"?"user policy":"project policy"),o=new Set){let i=[],s=[],a=e.rules.flatMap((c)=>{let d=sC(c,t,r);if(d.errors.length>0||!d.rulebook)return i.push(...d.errors),[];let u=d.rulebook;if(o.has(u.name))return s.push(`duplicate active rulebook name "${u.name}" for ${c}; keeping the first and ignoring this one, so its rules are not active; rename one of them in its rulebook file and in the rules config that lists it`),[];return o.add(u.name),[{rules:iC(u),rulebook:{source:n,spec:c,name:u.name,version:u.version,rules:u.rules.map((f)=>`${u.name}/${f.name}`)}}]}),l=a.flatMap((c)=>c.rules);return{rules:l,rulebooks:a.map((c)=>c.rulebook),knownRuleIds:new Set(l.map((c)=>c.name)),errors:i,warnings:s,canValidateOverrides:i.length===0}}function iC(e){if(e.rulebook_version===2)return e.rules.map((t)=>({name:`${e.name}/${t.name}`,command:t.command,block_args:[],match:t.match,reason:t.reason,intent:t.intent}));return e.rules.map((t)=>({...t,name:`${e.name}/${t.name}`,match:void 0}))}function sC(e,t,n){let r=aC(e),o=bd(t,r),i=cC(o,n);if("error"in i)return{rulebook:null,errors:[i.error]};if(i.content===null)return{rulebook:null,errors:[`missing rulebook file ${o} for ${e}; ${lC(e)}`]};let s=dC(i.content);if("problem"in s)return{rulebook:null,errors:[`invalid rulebook ${o}: ${s.problem}; fix that file`]};if(s.rulebook.name!==r)return{rulebook:null,errors:[`rulebook name "${s.rulebook.name}" in ${o} must match source "${e}"; fix that file`]};return{rulebook:s.rulebook,errors:[]}}function aC(e){return Eo(e)?Ms(e).name:e}function lC(e){return Eo(e)?`run ${yd} to vendor ${e}`:"create that file or remove that source from the rules config"}function cC(e,t){try{return{content:vo(br(t,e))}}catch(n){if(n instanceof he)return{error:n.message};throw n}}function dC(e){let t;try{t=JSON.parse(e)}catch{return{problem:"Invalid JSON"}}try{return{rulebook:Id(t)}}catch(n){return{problem:n instanceof Error?n.message:"invalid rulebook"}}}function uC(e,t){return[...new Set([...e?.transparent_wrappers??[],...t?.transparent_wrappers??[]])]}function mC(e,t){let n=(e?.command_tools??[]).map(Wd),r=(t?.command_tools??[]).map(Wd);return[...n,...r.filter((o)=>!n.some((i)=>i.name===o.name))]}function Wd(e){if(typeof e==="string")return{name:e};return e.cwd===void 0?{name:e.name}:{name:e.name,cwd:e.cwd}}function Fd(e,t){return e.flatMap((n)=>{let r=t[n.name];if(r==="off")return[];if(r&&typeof r==="object")return[{...n,intent:r.intent??n.intent,reason:r.reason}];return[n]})}function Gd(e,t,n){return Object.keys(e).filter((r)=>!t.has(r)).map((r)=>`unknown override key "${r}" in ${n}; only that override is ignored and other overrides and rules keep their configured state; correct or remove it in that file`)}function fC(e,t,n){return Object.keys(e).filter((r)=>t.has(r)).map((r)=>`project override cannot target user-scoped rule "${r}" in ${n}; only that override is ignored and the rule keeps its user-configured state; remove it from that file`)}function zd(e,t){return t.map((n)=>n.startsWith("Unable to access ")?n:`${e}: ${n}`)}function pC(e,t){return{rules:[],transparent_wrappers:[],command_tools:[],rulebooks:[],errors:[t],warnings:[],userConfigPath:e.userConfigPath,projectConfigPath:e.projectConfigPath}}function $d(){return{rules:[],rulebooks:[],knownRuleIds:new Set,errors:[],warnings:[],canValidateOverrides:!0}}import{existsSync as xC,readFileSync as AC}from"fs";var Ud=[{id:"git.ssh-env",category:"Git",label:"Git SSH environment override",description:"Blocks Git network operations with SSH environment overrides.",example:'GIT_SSH_COMMAND="./ssh-wrapper" git push',intent:"manual_only"},{id:"git.alias-config",category:"Git",label:"Git command-line alias",description:"Blocks command-line Git aliases that cannot be safely resolved.",example:"git -c alias.wipe='!rm -rf /' wipe",intent:"manual_only"},{id:"git.checkout-force",category:"Git",label:"Git checkout force",description:"Blocks forced checkout operations that discard local changes.",example:"git checkout --force main",intent:"use_alternative"},{id:"git.checkout-double-dash",category:"Git",label:"Git checkout path restore",description:"Blocks checkout path restores, with or without --.",example:"git checkout -- src/app.ts",intent:"use_alternative"},{id:"git.checkout-ref-path",category:"Git",label:"Git checkout ref and path",description:"Blocks checkout forms that mix a ref and path restore.",example:"git checkout HEAD -- src/app.ts",intent:"use_alternative"},{id:"git.checkout-pathspec-from-file",category:"Git",label:"Git checkout pathspec file",description:"Blocks checkout pathspec loading from a file.",example:"git checkout --pathspec-from-file=paths.txt",intent:"use_alternative"},{id:"git.checkout-ambiguous",category:"Git",label:"Git checkout ambiguous targets",description:"Blocks ambiguous checkout arguments that may restore paths.",example:"git checkout main src/app.ts",intent:"use_alternative"},{id:"git.switch-discard-changes",category:"Git",label:"Git switch discard changes",description:"Blocks branch switches that explicitly discard local changes.",example:"git switch --discard-changes main",intent:"use_alternative"},{id:"git.switch-force",category:"Git",label:"Git switch force",description:"Blocks forced branch switches.",example:"git switch --force main",intent:"use_alternative"},{id:"git.restore-worktree",category:"Git",label:"Git restore worktree",description:"Blocks worktree restore operations.",example:"git restore --worktree src/app.ts",intent:"use_alternative"},{id:"git.restore-unstaged",category:"Git",label:"Git restore unstaged",description:"Blocks unstaged restore operations.",example:"git restore src/app.ts",intent:"use_alternative"},{id:"git.reset-hard",category:"Git",label:"Git reset hard",description:"Blocks hard resets.",example:"git reset --hard",intent:"use_alternative"},{id:"git.reset-merge",category:"Git",label:"Git reset merge",description:"Blocks merge resets.",example:"git reset --merge",intent:"use_alternative"},{id:"git.clean-force",category:"Git",label:"Git clean force",description:"Blocks forced clean operations.",example:"git clean -fd",intent:"use_alternative"},{id:"git.rm-force",category:"Git",label:"Git rm force",description:"Blocks forced removal of tracked files from the working tree.",example:"git rm -rf .",intent:"use_alternative"},{id:"git.push-force",category:"Git",label:"Git push force",description:"Blocks force pushes.",example:"git push --force origin main",intent:"use_alternative"},{id:"git.push-delete",category:"Git",label:"Git push delete",description:"Blocks remote ref deletion through push.",example:"git push --delete origin old-branch",intent:"manual_only"},{id:"git.push-mirror",category:"Git",label:"Git push mirror",description:"Blocks mirror pushes that can force-update or delete remote refs.",example:"git push --mirror origin",intent:"manual_only"},{id:"git.branch-force-delete",category:"Git",label:"Git branch force delete",description:"Blocks forced branch deletion.",example:"git branch -D old-branch",intent:"use_alternative"},{id:"git.rebase-abort",category:"Git",label:"Git rebase abort",description:"Blocks rebase abort operations.",example:"git rebase --abort",intent:"use_alternative"},{id:"git.merge-abort",category:"Git",label:"Git merge abort",description:"Blocks merge abort operations.",example:"git merge --abort",intent:"use_alternative"},{id:"git.tag-delete",category:"Git",label:"Git tag delete",description:"Blocks tag deletion.",example:"git tag --delete v1.0.0",intent:"manual_only"},{id:"git.reflog-delete",category:"Git",label:"Git reflog delete",description:"Blocks reflog deletion.",example:"git reflog delete HEAD@{1}",intent:"manual_only"},{id:"git.stash-drop",category:"Git",label:"Git stash drop",description:"Blocks dropping stash entries.",example:"git stash drop stash@{0}",intent:"use_alternative"},{id:"git.stash-clear",category:"Git",label:"Git stash clear",description:"Blocks clearing all stash entries.",example:"git stash clear",intent:"manual_only"},{id:"git.worktree-remove-force",category:"Git",label:"Git worktree force remove",description:"Blocks forced worktree removal.",example:"git worktree remove --force ../feature",intent:"use_alternative"},{id:"rm.recursive-force-root-or-home",category:"Filesystem",label:"rm -rf root or home",description:"Blocks recursive forced removal of root or home paths.",example:"rm -rf /",intent:"hard_stop",catastrophic:!0},{id:"rm.git-metadata",category:"Filesystem",label:"rm Git metadata",description:"Blocks removal of protected Git metadata and hooks.",example:"rm -rf .git",intent:"hard_stop",catastrophic:!0},{id:"rm.recursive-force-dynamic-target",category:"Filesystem",label:"rm -rf dynamic target",description:"Blocks recursive forced removal with dynamic targets in strict mode.",example:'rm -rf "$target"',intent:"scope_down",activationCapability:"fail_closed"},{id:"rm.recursive-force-home-cwd",category:"Filesystem",label:"rm -rf from home cwd",description:"Blocks recursive forced removal while working in home.",example:'cd "$HOME" && rm -rf build',intent:"scope_down"},{id:"rm.recursive-force-cwd-self",category:"Filesystem",label:"rm -rf current directory",description:"Blocks recursive forced removal of the current directory.",example:"rm -rf .",intent:"scope_down"},{id:"rm.recursive-force-outside-cwd",category:"Filesystem",label:"rm -rf outside cwd",description:"Blocks recursive forced removal outside the original cwd.",example:"rm -rf ../outside",intent:"scope_down"},{id:"rm.recursive-force-paranoid",category:"Filesystem",label:"rm -rf paranoid mode",description:"Blocks non-temp recursive forced removal when paranoid rm is enabled.",example:"rm -rf ./cache",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"powershell.remove-item-root-or-home",category:"PowerShell",label:"Remove-Item root or home",description:"Blocks PowerShell Remove-Item targeting root or home paths.",example:"Remove-Item C:\\",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-recursive-force-root-or-home",category:"PowerShell",label:"Remove-Item recursive force root or home",description:"Blocks recursive forced PowerShell removal of root or home paths.",example:"Remove-Item C:\\ -Recurse -Force",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-git-metadata",category:"PowerShell",label:"Remove-Item Git metadata",description:"Blocks PowerShell removal of protected Git metadata and hooks.",example:"Remove-Item .git -Recurse -Force",intent:"hard_stop",catastrophic:!0},{id:"powershell.remove-item-recursive-force-dynamic-target",category:"PowerShell",label:"Remove-Item recursive force dynamic target",description:"Blocks recursive forced PowerShell removal with dynamic targets in strict mode.",example:"Remove-Item $target -Recurse -Force",intent:"scope_down",activationCapability:"fail_closed"},{id:"powershell.remove-item-recursive-force-home-cwd",category:"PowerShell",label:"Remove-Item recursive force from home cwd",description:"Blocks recursive forced PowerShell removal while working in home.",example:"Set-Location $HOME; Remove-Item ./build -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-cwd-self",category:"PowerShell",label:"Remove-Item recursive force current directory",description:"Blocks recursive forced PowerShell removal of the current directory.",example:"Remove-Item . -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-outside-cwd",category:"PowerShell",label:"Remove-Item recursive force outside cwd",description:"Blocks recursive forced PowerShell removal outside the original cwd.",example:"Remove-Item ../outside -Recurse -Force",intent:"scope_down"},{id:"powershell.remove-item-recursive-force-paranoid",category:"PowerShell",label:"Remove-Item recursive force paranoid mode",description:"Blocks non-temp recursive forced PowerShell removal when paranoid rm is enabled.",example:"Remove-Item ./cache -Recurse -Force",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"powershell.remove-item-pipeline-dynamic-target",category:"PowerShell",label:"Remove-Item pipeline dynamic target",description:"Blocks PowerShell Remove-Item with unverifiable pipeline input in strict mode.",example:"Get-ChildItem . -Recurse | Remove-Item -Force",intent:"scope_down",activationCapability:"fail_closed"},{id:"powershell.nested-recursive-delete-unread",category:"PowerShell",label:"Nested PowerShell recursive delete not read",description:"Blocks a recursive delete handed to powershell or pwsh in any form other than literal -Command script words.",example:"pwsh -WorkingDirectory C:\\ -c 'Remove-Item -Recurse -Force *'",intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-root-or-home",category:"Command Prompt",label:"cmd recursive delete root or home",description:"Blocks cmd rmdir /s or del /s of root or home paths.",example:"cmd /c rmdir /s /q C:\\",intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-escaped-quote",category:"Command Prompt",label:"cmd recursive delete with escaped quotes",description:"Blocks cmd rmdir /s or del /s whose quoting can reach cmd as \\\" and split the target down to the drive root.",example:'cmd /c "rmdir /s /q \\"build output\\""',intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-git-metadata",category:"Command Prompt",label:"cmd recursive delete Git metadata",description:"Blocks cmd rmdir /s or del /s of protected Git metadata and hooks.",example:"cmd /c rmdir /s /q .git",intent:"hard_stop",catastrophic:!0},{id:"cmd.recursive-delete-dynamic-target",category:"Command Prompt",label:"cmd recursive delete dynamic target",description:"Blocks cmd rmdir /s or del /s with wildcard or variable targets in strict mode.",example:"cmd /c del /s /q *.log",intent:"scope_down",activationCapability:"fail_closed"},{id:"cmd.recursive-delete-home-cwd",category:"Command Prompt",label:"cmd recursive delete from home cwd",description:"Blocks cmd rmdir /s or del /s while working in home.",example:"Set-Location $HOME; cmd /c rmdir /s /q build",intent:"scope_down"},{id:"cmd.recursive-delete-cwd-self",category:"Command Prompt",label:"cmd recursive delete current directory",description:"Blocks cmd rmdir /s or del /s of the current directory.",example:"cmd /c rmdir /s /q .",intent:"scope_down"},{id:"cmd.recursive-delete-outside-cwd",category:"Command Prompt",label:"cmd recursive delete outside cwd",description:"Blocks cmd rmdir /s or del /s outside the original cwd.",example:"cmd /c rmdir /s /q ..\\outside",intent:"scope_down"},{id:"cmd.recursive-delete-paranoid",category:"Command Prompt",label:"cmd recursive delete paranoid mode",description:"Blocks non-temp cmd rmdir /s or del /s when paranoid rm is enabled.",example:"cmd /c rmdir /s /q build",intent:"scope_down",activationCapability:"paranoid_rm"},{id:"find.delete",category:"Filesystem",label:"find delete",description:"Blocks unsafe find -delete operations.",example:"find . -delete",intent:"scope_down"},{id:"find.delete-git-metadata",category:"Filesystem",label:"find delete Git metadata",description:"Blocks find -delete operations selecting protected Git metadata and hooks.",example:"find .git -delete",intent:"hard_stop",catastrophic:!0},{id:"find.exec-rm-recursive-force",category:"Filesystem",label:"find exec rm -rf",description:"Blocks find -exec rm -rf operations.",example:"find . -exec rm -rf {} +",intent:"scope_down"},{id:"rsync.delete",category:"Filesystem",label:"rsync delete",description:"Blocks rsync delete modes whose destination is outside the cwd, a temp root, or a variable.",example:'rsync -a --delete "$SRC/" "$DST/"',intent:"scope_down"},{id:"dd.device-write",category:"Filesystem",label:"dd device write",description:"Blocks dd writing to a /dev device other than /dev/null, /dev/zero, or /dev/full.",example:"dd if=/dev/zero of=/dev/sda",intent:"manual_only"},{id:"mkfs.device",category:"Filesystem",label:"Filesystem format on a device",description:"Blocks mkfs, mke2fs, and newfs formatting a /dev device.",example:"mkfs.ext4 /dev/sda1",intent:"manual_only"},{id:"disk.erase",category:"Filesystem",label:"Disk erase or repartition",description:"Blocks diskutil erase and partition verbs, wipefs -a/-o, sgdisk writes, and parted label or partition edits on a /dev device.",example:"diskutil eraseDisk APFS Untitled disk4",intent:"manual_only"},{id:"shred.target",category:"Filesystem",label:"shred target",description:"Blocks shred against any target, including shred --help and shred --version.",example:"shred -u secret.txt",intent:"use_alternative"},{id:"redirect.block-device",category:"Filesystem",label:"Redirect onto a disk device",description:"Blocks output redirects whose literal target is a disk device path under /dev.",example:"cat disk.img > /dev/sda",intent:"manual_only"},{id:"network.cloud-metadata",category:"Network",label:"Cloud metadata endpoint",description:"Blocks HTTP clients, raw socket tools, and code interpreters naming a cloud metadata host (169.254.169.254, fd00:ec2::254, 169.254.170.2, 169.254.170.23, fd00:ec2::23, metadata.google.internal, metadata.goog, 100.100.100.200).",example:"curl http://169.254.169.254/latest/meta-data/iam/security-credentials/",intent:"manual_only"},{id:"network.upload-remote",category:"Network",label:"Data upload to a remote host",description:"Blocks curl and wget requests that send a body or upload a file in strict mode unless every URL is loopback (localhost, *.localhost, 127.0.0.0/8, 0.0.0.0, [::1]).",example:"curl -T backup.tar https://uploads.example.com/",intent:"manual_only",activationCapability:"fail_closed"},{id:"unshare.user-namespace",category:"Execution",label:"unshare user namespace",description:"Blocks unshare creating a user namespace: -U/--user, -r/--map-root-user, -c/--map-current-user, --map-user(s), --map-group(s), or --map-auto.",example:"unshare -r id",intent:"manual_only"},{id:"interpreter.dangerous-command",category:"Execution",label:"Interpreter dangerous command",description:"Blocks interpreter one-liners containing dangerous commands.",example:`python -c "import os; os.system('rm -rf /')"`,intent:"use_alternative"},{id:"interpreter.one-liner-paranoid",category:"Execution",label:"Interpreter one-liner paranoid mode",description:"Blocks interpreter one-liners when paranoid interpreters is enabled.",example:'python -c "print(1)"',intent:"use_alternative",activationCapability:"paranoid_interpreters"},{id:"awk.system-dynamic",category:"Execution",label:"Awk dynamic system call",description:"Blocks awk system calls that cannot be safely analyzed.",example:"awk '{ system($0) }'",intent:"stop_and_explain"},{id:"xargs.rm-recursive-force-dynamic",category:"Execution",label:"xargs dynamic rm -rf",description:"Blocks xargs rm -rf with dynamic input.",example:"printf / | xargs rm -rf",intent:"scope_down"},{id:"xargs.shell-dynamic",category:"Execution",label:"xargs dynamic shell",description:"Blocks xargs shell execution with dynamic input.",example:"xargs r$(printf m) -rf",intent:"scope_down"},{id:"parallel.rm-recursive-force-dynamic",category:"Execution",label:"parallel dynamic rm -rf",description:"Blocks parallel rm -rf with dynamic input.",example:"printf / | parallel rm -rf",intent:"scope_down"},{id:"parallel.shell-dynamic",category:"Execution",label:"parallel dynamic shell",description:"Blocks parallel shell execution with dynamic input.",example:"parallel r$(printf m) -rf ::: child",intent:"scope_down"},{id:"parallel.command-stream-dynamic",category:"Execution",label:"parallel dynamic command stream",description:"Blocks parallel command streams from dynamic input.",example:"parallel --dry-run",intent:"scope_down"},{id:"shell.dynamic-structure",category:"Execution",label:"Dynamic command structure",description:"Blocks guarded subcommands and options assembled from substitution output in strict mode.",example:"git reset $(printf --hard)",intent:"stop_and_explain",activationCapability:"fail_closed"},{id:"shell.dynamic-executable",category:"Execution",label:"Dynamic executable name",description:"Blocks executable names assembled from command substitution output in strict mode.",example:"$(printf r)m -rf /",intent:"manual_only",activationCapability:"fail_closed"},{id:"raw-text.dangerous-command",category:"Execution",label:"Raw text dangerous command",description:"Blocks dangerous commands detected in raw command text.",example:"git reset --hard 'unterminated",intent:"stop_and_explain"}],Zs=new Set(Ud.map((e)=>e.id)),Io=Ud,gC=new Map(Io.map((e)=>[e.id,e.intent]));function b(e,t){return{id:e,reason:t,intent:gC.get(e)??"manual_only"}}var Xs=[{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"}],ko={id:"secret.pattern.env-variant",category:"Pattern",label:".env.*",description:"Blocks environment-specific .env variants."},hC=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],yC=[{idSlug:"kube-config",label:"~/.kube/config",directoryParts:[".kube"],basename:"config"},{idSlug:"docker-config",label:"~/.docker/config.json",directoryParts:[".docker"],basename:"config.json"}],Qs=[{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"]},...yC.flatMap((e)=>hC.map((t)=>({id:["secret.home",e.idSlug,t.slice(1)].join("."),category:"Home path",label:[e.label,t].join(""),description:["Blocks home ",e.label,t," credential backup files."].join(""),suffixParts:[...e.directoryParts,[e.basename,t].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 Oo=[{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.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","<project>/.codex/config.toml"]},{id:"secret.cli.gemini",category:"Coding CLI credential",label:"Gemini CLI credentials",paths:["~/.gemini/oauth_creds.json","~/.gemini/mcp-oauth-tokens.json","~/.gemini/a2a-oauth-tokens.json","~/.gemini/gemini-credentials.json"]},{id:"secret.cli.gemini.config",category:"Coding CLI config",label:"Gemini CLI config",paths:["~/.gemini/settings.json","~/.gemini/google_accounts.json","<project>/.gemini/settings.json","/Library/Application Support/GeminiCli/settings.json","/etc/gemini-cli/settings.json"]},{id:"secret.cli.copilot-cli",category:"Coding CLI credential",label:"GitHub Copilot CLI credentials",paths:["~/.copilot/config.json","~/.copilot/mcp-oauth-config","~/.copilot/mcp-secrets"]},{id:"secret.cli.copilot-cli.config",category:"Coding CLI config",label:"GitHub Copilot CLI config",paths:["~/.copilot/mcp-config.json"]},{id:"secret.cli.kimi-code",category:"Coding CLI credential",label:"Kimi Code credentials",paths:["~/.kimi-code/server.token","~/.kimi-code/credentials","~/.kimi/credentials","~/.kimi/mcp-oauth"]},{id:"secret.cli.kimi-code.config",category:"Coding CLI config",label:"Kimi Code config",paths:["~/.kimi-code/config.toml","~/.kimi-code/mcp.json","~/.kimi/config.toml","~/.kimi/config.json","~/.kimi/config.json.bak","~/.kimi/mcp.json","<project>/.kimi-code/mcp.json"]},{id:"secret.cli.opencode",category:"Coding CLI credential",label:"OpenCode credentials",paths:["~/.local/share/opencode/auth.json","~/.local/share/opencode/mcp-auth.json","~/.local/share/opencode/opencode.db"]},{id:"secret.cli.opencode.config",category:"Coding CLI config",label:"OpenCode config",paths:["~/.config/opencode/opencode.json","~/.config/opencode/opencode.jsonc","~/.config/opencode/config.json","/Library/Application Support/opencode/opencode.json","/etc/opencode/opencode.json","<project>/opencode.json","<project>/opencode.jsonc"]},{id:"secret.cli.pi",category:"Coding CLI credential",label:"Pi credentials",paths:["~/.pi/agent/auth.json"]},{id:"secret.cli.pi.config",category:"Coding CLI config",label:"Pi config",paths:["~/.pi/agent/models.json"]},{id:"secret.cli.amp",category:"Coding CLI credential",label:"Amp Code credentials",paths:["~/.local/share/amp/secrets.json","~/.amp/oauth"]},{id:"secret.cli.amp.config",category:"Coding CLI config",label:"Amp Code config",paths:["~/.config/amp/settings.json","~/.config/amp/settings.jsonc","<project>/.amp/settings.json","<project>/.amp/settings.jsonc"]},{id:"secret.cli.cursor",category:"Coding CLI credential",label:"Cursor CLI credentials",paths:["~/.cursor/auth.json","~/.config/cursor/auth.json","~/.cursor/projects/<name>/mcp-auth.json"]},{id:"secret.cli.cursor.config",category:"Coding CLI config",label:"Cursor CLI config",paths:["~/.cursor/mcp.json","<project>/.cursor/mcp.json"]},{id:"secret.cli.grok-build",category:"Coding CLI credential",label:"Grok Build credentials",paths:["~/.grok/auth.json","~/.grok/mcp_credentials.json"]},{id:"secret.cli.grok-build.config",category:"Coding CLI config",label:"Grok Build config",paths:["~/.grok/config.toml","~/.grok/managed_config.toml","~/.grok/requirements.toml","<project>/.grok/config.toml","/etc/grok/managed_config.toml","/etc/grok/requirements.toml"]},{id:"secret.cli.droid",category:"Coding CLI credential",label:"Factory Droid credentials",paths:["~/.factory/auth.encrypted","~/.factory/auth.v2.file","~/.factory/auth.v2.key","~/.factory/auth.v2.loginkeychain"]},{id:"secret.cli.droid.config",category:"Coding CLI config",label:"Factory Droid config",paths:["~/.factory/settings.json","~/.factory/hooks.json","~/.factory/mcp.json","<project>/.factory/mcp.json"]},{id:"secret.cli.devin",category:"Coding CLI credential",label:"Devin CLI credentials",paths:["~/.local/share/devin/credentials.toml","~/.local/share/devin/mcp/oauth"]},{id:"secret.cli.devin.config",category:"Coding CLI config",label:"Devin CLI config",paths:["~/.config/devin/config.json"]}],Hd=[{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"}],SC=[".bak",".backup",".copy",".disabled",".key",".old",".orig",".pem",".save",".tmp"],Js=Hd.map((e)=>({id:`secret.variant.${e.slug}.separator`,category:"Variant",label:`${e.label}-* / ${e.label}_*`,description:`Blocks ${e.label} variants with dash or underscore suffixes.`,prefix:e.prefix})),ea=Hd.flatMap((e)=>SC.map((t)=>({id:`secret.variant.${e.slug}.${t.slice(1)}`,category:"Variant",label:`${e.label}${t}`,description:`Blocks ${e.label}${t} private credential variants.`,prefix:e.prefix,suffix:t}))),Er={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)$/},ta=["agilekeychain","asc","bek","cscfg","fve","gnucash","jks","keychain","kwallet","mdf","ovpn","p12","pcap","pem","pfx","pkcs12","psafe3","rdp","sdf","tblk","tpm"].map((e)=>({id:`secret.ext.${e}`,category:"Extension",label:`.${e}`,description:`Blocks files with the .${e} extension.`,extension:e})),na=[{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?$/}],CC=[...Xs,ko,...Qs,...Js,...ea,Er,...ta,...na,...Oo].map((e)=>({id:e.id,category:e.category,label:e.label,...e.category==="Coding CLI config"?{defaultOff:!0}:{},..."paths"in e?{paths:e.paths}:{description:e.description}})),Do=new Set(Oo.flatMap((e)=>e.category==="Coding CLI config"?[e.id]:[])),ra=new Set(CC.map((e)=>e.id));import{isAbsolute as oa,join as bC,normalize as vC,sep as Mo}from"path";var No=process.platform==="win32",jd=/[*?]/;function ia(e){let t=e.trim(),n=/^(.*)\/\*\*\/([^/*?\\]+)$/.exec(No?t.replaceAll("\\","/"):t);if(!n)return null;let r=n[1]??"",o=n[2]??"";if(jd.test(r)||o==="."||o==="..")return null;return{root:r||"/",name:o}}function Rr(e,t){if(e==="~")return t;if(e.startsWith("~/"))return`${t}${e.slice(1)}`;return e}function sa(e,t){if(typeof e!=="string"||e.trim()==="")return"must be a non-empty path string";let n=Rr(e.trim(),t);if(!oa(n))return"must be an absolute path or start with ~/";return wr(n,t)}function aa(e,t){let n=Vd(e,t);if(n===null)return"must be a non-empty path string";if(!oa(n))return null;if(wr(n,t)===null)return null;return"cannot be the home directory or a path above it (this would block every command the agent runs)"}var EC="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",RC="cannot cover the guard's own configuration";function Vd(e,t){if(typeof e!=="string"||e.trim()==="")return null;let n=e.trim(),r=No?n.replaceAll("\\","/"):n;return Rr(r.replace(/^\$(?:\{HOME\}|HOME(?=\/|$))/,"~"),t)}function la(e,t){let n=Vd(e,t);if(n===null)return"must be a non-empty path string";let r=ia(n)?.root??n;if(jd.test(r))return"supports only a folder followed by **/ and an exact file name, such as ~/code/**/.env.local";if(!oa(r))return null;if(wr(r,t)!==null)return EC;return wC(r,t)?RC:null}function wC(e,t){let n=Lo(e),r=Lo(bC(t,".cc-safety-net"));return n===r||n.startsWith(`${r}${Mo}`)}function wr(e,t){let n=Lo(e),r=Lo(t);if(n===r)return"cannot be the home directory";let o=n.endsWith(Mo)?n:`${n}${Mo}`;if(r.startsWith(o))return"cannot contain the home directory";return null}function Lo(e){let t=vC(e);if(No)t=t.replace(/\//g,"\\").toLowerCase();if(t.length>(No?3:1)&&t.endsWith(Mo))t=t.slice(0,-1);return t}var qd=30,Wo=1,Fo=365;function Kd(e){if(typeof e!=="number"||!Number.isInteger(e))return 30;if(e<1)return 1;return e>365?365:e}var Yd=new Set(Io.filter((e)=>e.catastrophic).map((e)=>e.id));function O(e,t){if(!e)return null;if(Yd.has(e.id))return e;if(t?.destructiveCommandProtectionEnabled===!1)return null;let n=t?.effectiveDestructiveCommandRules[e.id];return n&&!n.enabled?null:e}function ae(e,t,n){if(Yd.has(t))return!0;if(e?.destructiveCommandProtectionEnabled===!1)return!1;return e?.effectiveDestructiveCommandRules[t]?.enabled??n}function Zd(e,t){return Object.freeze(Object.fromEntries(Io.map((n)=>{let r=n.activationCapability?t[n.activationCapability]:void 0,o=r?.enabled??!0,i=e.destructiveCommandRuleOverrides[n.id],s=n.catastrophic?{enabled:!0,inheritedEnabled:!0,changesInherited:!1,source:"catastrophic",...i?{override:i}:{}}:e.destructiveCommandProtectionEnabled?i?{enabled:i==="on",inheritedEnabled:o,changesInherited:i==="on"!==o,source:"rule_override",...n.activationCapability?{activationCapability:n.activationCapability}:{},override:i}:{enabled:o,inheritedEnabled:o,changesInherited:!1,source:r?.source??"built_in_default",...n.activationCapability?{activationCapability:n.activationCapability}:{}}:{enabled:!1,inheritedEnabled:o,changesInherited:!1,source:"master_disabled",...n.activationCapability?{activationCapability:n.activationCapability}:{},...i?{override:i}:{}};return[n.id,Object.freeze(s)]})))}function Xd(e,t){return Object.freeze({...e,effectiveDestructiveCommandRules:Zd(e,t)})}var Qd={standard:0,strict:1,paranoid:2};function tu(e,t,n=!1,r=e.safety.level){let o=_C(e,t,r),i=new Set(n?o.map((d)=>d.field):[]),s=(d,u)=>i.has(d)?void 0:u,a=(d,u)=>Object.fromEntries(Object.entries(u??{}).filter(([f])=>!i.has(`${d}.${f}`))),l=(d,u)=>u?.filter((f)=>!i.has(`${d}.${f}`));return{policy:{version:1,safety:{level:s("safety.level",t.safety?.level)??e.safety.level,overrides:{...e.safety.overrides,...a("safety.overrides",t.safety?.overrides)}},workflow:{worktree_mode:s("workflow.worktree_mode",t.workflow?.worktree_mode)??e.workflow.worktree_mode},destructive_command_protection:{enabled:s("destructive_command_protection.enabled",t.destructive_command_protection?.enabled)??e.destructive_command_protection.enabled,overrides:{...e.destructive_command_protection.overrides,...a("destructive_command_protection.overrides",t.destructive_command_protection?.overrides)},allow_paths:ca(e.destructive_command_protection.allow_paths,l("destructive_command_protection.allow_paths",t.destructive_command_protection?.allow_paths))},secret_protection:{enabled:s("secret_protection.enabled",t.secret_protection?.enabled)??e.secret_protection.enabled,overrides:{...e.secret_protection.overrides,...a("secret_protection.overrides",t.secret_protection?.overrides)},deny_paths:ca(e.secret_protection.deny_paths,t.secret_protection?.deny_paths),allow_paths:ca(e.secret_protection.allow_paths,l("secret_protection.allow_paths",t.secret_protection?.allow_paths))},audit:e.audit},weakenings:o.map((d)=>d.message)}}function ca(e,t){return[...new Set([...e,...t??[]])]}function _C(e,t,n){let r=t.safety?.level,o=yo[n];return[...r&&Qd[r]<Qd[e.safety.level]?[{field:"safety.level",message:`project policy lowers level: ${e.safety.level} -> ${r}`}]:[],...xn.flatMap((i)=>t.safety?.overrides?.[i]===!1&&(e.safety.overrides[i]??o[i])?[{field:`safety.overrides.${i}`,message:`project policy disables ${i}`}]:[]),...t.workflow?.worktree_mode===!0&&!e.workflow.worktree_mode?[{field:"workflow.worktree_mode",message:"project policy enables worktree mode relaxations"}]:[],...t.destructive_command_protection?.enabled===!1&&e.destructive_command_protection.enabled?[{field:"destructive_command_protection.enabled",message:"project policy disables destructive command protection"}]:[],...t.secret_protection?.enabled===!1&&e.secret_protection.enabled?[{field:"secret_protection.enabled",message:"project policy disables secret protection"}]:[],...Jd("destructive_command_protection.overrides",t.destructive_command_protection?.overrides,(i)=>e.destructive_command_protection.enabled&&e.destructive_command_protection.overrides[i]!=="off"),...Jd("secret_protection.overrides",t.secret_protection?.overrides,(i)=>e.secret_protection.enabled&&(e.secret_protection.overrides[i]==="on"?!0:e.secret_protection.overrides[i]!=="off"&&!Do.has(i))),...e.destructive_command_protection.enabled?eu(e.destructive_command_protection.allow_paths,t.destructive_command_protection?.allow_paths).map((i)=>({field:`destructive_command_protection.allow_paths.${i}`,message:`project policy adds destructive allow path: ${i}`})):[],...e.secret_protection.enabled?eu(e.secret_protection.allow_paths,t.secret_protection?.allow_paths).map((i)=>({field:`secret_protection.allow_paths.${i}`,message:`project policy adds secret allow path: ${i}`})):[]]}function Jd(e,t,n){return Object.entries(t??{}).flatMap(([r,o])=>o==="off"&&n(r)?[{field:`${e}.${r}`,message:`project policy disables rule ${r}`}]:[])}function eu(e,t){return(t??[]).filter((n)=>!e.includes(n))}var ua=new Set(["standard","strict","paranoid"]),ou={version:1,safety:{level:"standard",overrides:{}},workflow:{worktree_mode:!1},destructive_command_protection:{enabled:!0,overrides:{},allow_paths:[]},secret_protection:{enabled:!0,overrides:{},deny_paths:[],allow_paths:[]},audit:{retention_days:qd}};function iu(e,t){let n=WC(Vt(e,t),e.home),r=Sd(e,t)?{exists:!1,policy:Yt(),errors:[]}:zo(An(t.cwd),e.home),o=TC(r.parsed,e.home),i=dt(J.projectTightenOnly,e.env),s=n.gui??ou,a=Object.keys(o.policy).length>0?tu(s,o.policy,i,rd(s.safety.level,e.env)):void 0,l=[...n.errors,...r.errors,...o.diagnostics],c=(n.fallback==="defaults"&&a?"salvaged":n.fallback)??(n.gui?void 0:r.fallback)??(l.length>0?"salvaged":void 0),d=o.policy.safety?.level&&a?.policy.safety.level===o.policy.safety.level?"project":n.levelPresent?"user":"default";return{...a?_r(a.policy):n.policy,errors:l,...c?{fallback:c}:{},...r.exists?{policyScopes:{levelScope:d,weakenings:a?.weakenings??[],weakeningsIgnored:i}}:{}}}var PC="project policy audit settings are ignored; audit is user scope only";function TC(e,t){if(!Me(e))return{policy:{},diagnostics:[]};let n=Me(e.safety)?e.safety:{},r=Me(e.workflow)?e.workflow:{},o=Me(e.destructive_command_protection)?e.destructive_command_protection:{},i=Me(e.secret_protection)?e.secret_protection:{},s={...ua.has(n.level)?{level:n.level}:{},...Me(n.overrides)?nu({overrides:su(n.overrides,xn,["safety","overrides"],Kt)}):{}},a={...typeof o.enabled==="boolean"?{enabled:o.enabled}:{},...o.overrides!==void 0?{overrides:Go(o.overrides,Zs,lu,Kt)}:{},...o.allow_paths!==void 0?{allow_paths:Tn(o.allow_paths,sa,t,["destructive_command_protection","allow_paths"],Kt)}:{}},l={...typeof i.enabled==="boolean"?{enabled:i.enabled}:{},...i.overrides!==void 0?{overrides:Go(i.overrides,ra,cu,Kt)}:{},...i.deny_paths!==void 0?{deny_paths:Tn(i.deny_paths,aa,t,["secret_protection","deny_paths"],Kt)}:{},...i.allow_paths!==void 0?{allow_paths:Tn(i.allow_paths,la,t,["secret_protection","allow_paths"],Kt)}:{}};return{policy:nu({safety:s,workflow:typeof r.worktree_mode==="boolean"?{worktree_mode:r.worktree_mode}:{},destructive_command_protection:a,secret_protection:l}),diagnostics:e.audit===void 0?[]:[PC]}}function su(e,t,n,r){return Object.fromEntries(t.flatMap((o)=>{let i=e[o];if(typeof i==="boolean")return[[o,i]];if(i!==void 0)r(T([...n,o],ma));return[]}))}function nu(e){return Object.fromEntries(Object.entries(e).flatMap((t)=>Object.keys(t[1]).length>0?[t]:[]))}var Kt=()=>{return},ma="must be a boolean",fa="must be an object if provided",au=`must be an integer between ${Wo} and ${Fo}`,lu={path:["destructive_command_protection","overrides"],label:"destructive command"},cu={path:["secret_protection","overrides"],label:"secret protection"},IC=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function kC(e,t){let n=[];return{policy:du(e,t,(o)=>{n.push(o)}),issues:n}}function OC(e,t){return du(e,t,Kt)}function du(e,t,n){if(!Me(e))return n(T([],"Config must be an object")),Yt();if(e.version!==1)n(T(["version"],"must be 1"));let r=Pn(e.safety,["safety"],["level","overrides"],n),o=Pn(r.overrides,["safety","overrides"],xn,n),i=Pn(e.workflow,["workflow"],["worktree_mode"],n),s=Pn(e.destructive_command_protection,["destructive_command_protection"],["enabled","overrides","allow_paths"],n),a=Pn(e.secret_protection,["secret_protection"],["enabled","overrides","deny_paths","allow_paths"],n),l=Pn(e.audit,["audit"],["retention_days"],n);return uu(e,IC,[],n),{version:1,safety:{level:DC(r.level,n),overrides:su(o,xn,["safety","overrides"],n)},workflow:{worktree_mode:da(i.worktree_mode,["workflow","worktree_mode"],!1,n)},destructive_command_protection:{enabled:da(s.enabled,["destructive_command_protection","enabled"],!0,n),overrides:Go(s.overrides,Zs,lu,n),allow_paths:Tn(s.allow_paths,sa,t,["destructive_command_protection","allow_paths"],n)},secret_protection:{enabled:da(a.enabled,["secret_protection","enabled"],!0,n),overrides:Go(a.overrides,ra,cu,n),deny_paths:Tn(a.deny_paths,aa,t,["secret_protection","deny_paths"],n),allow_paths:Tn(a.allow_paths,la,t,["secret_protection","allow_paths"],n)},audit:{retention_days:MC(l.retention_days,n)}}}function Pn(e,t,n,r){if(e===void 0)return{};if(!Me(e))return r(T(t,fa)),{};return uu(e,n,t,r),e}function uu(e,t,n,r){for(let o of Object.keys(e).filter((i)=>!t.includes(i)))r({path:n,message:o,kind:"unknownKeys"})}function DC(e,t){if(e===void 0)return"standard";if(ua.has(e))return e;return t(T(["safety","level"],'must be "standard", "strict", or "paranoid"')),"standard"}function da(e,t,n,r){if(typeof e==="boolean")return e;if(e!==void 0)r(T(t,ma));return n}function MC(e,t){if(!(e===void 0||typeof e==="number"&&Number.isInteger(e)&&e>=Wo&&e<=Fo))t(T(["audit","retention_days"],au));return Kd(e)}function Go(e,t,n,r){if(e===void 0)return{};if(!Me(e))return r(T(n.path,fa)),{};return Object.fromEntries(Object.entries(e).flatMap(([o,i])=>{if(!t.has(o))return r({path:[...n.path,o],message:`unknown ${n.label} rule id "${o}"`,kind:"key"}),[];if(i==="on"||i==="off")return[[o,i]];return r(T([...n.path,o],'must be "on" or "off"')),[]}))}function Tn(e,t,n,r,o){if(e===void 0)return[];if(!Array.isArray(e))return o(T(r,"must be an array of paths")),[];return e.flatMap((i,s)=>{let a=t(i,n);if(a===null)return[i];return o(typeof i==="string"?se([...r,s],a):T([...r,s],a)),[]})}function Me(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function Yt(){return structuredClone(ou)}function zo(e,t){if(!xC(e))return{exists:!1,policy:Yt(),errors:[]};try{let n=AC(e,"utf-8");if(!n.trim())return{exists:!0,policy:Yt(),errors:[`${e}: Config file is empty`],fallback:"defaults"};let r=JSON.parse(n),o=kC(r,t);if(o.issues.length===0)return{exists:!0,parsed:r,policy:o.policy,errors:[]};return{exists:!0,parsed:r,policy:o.policy,errors:o.issues.map((i)=>`${e}: ${LC(i)}`),fallback:Me(r)?"salvaged":"defaults"}}catch(n){let r=n instanceof Error?n.message:String(n);return{exists:!0,policy:Yt(),errors:[`${e}: ${n instanceof SyntaxError?"Invalid JSON":r}`],fallback:"defaults"}}}var NC=new Map([["Config must be an object","not a JSON object"],["must be 1","not 1"],[fa,"not an object"],['must be "standard", "strict", or "paranoid"',"not one of standard, strict, paranoid"],[ma,"not a boolean"],['must be "on" or "off"','not "on" or "off"'],["must be an array of paths","not an array"],[au,`not an integer between ${Wo} and ${Fo}`]]);function LC(e){let t=Ks(e.path);if(e.kind==="unknownKeys")return`${t===""?"":`${t}.`}${e.message}: unknown field`;if(e.kind==="key")return`${t}: unknown rule id`;let n=NC.get(e.message)??e.message;return t===""?n:`${t}: ${n}`}function WC(e,t){let n=zo(e,t);if(!n.exists){let r=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!Me(r))return{policy:_r(Yt()),errors:[]};let o=OC(r,t);return{policy:_r(o),gui:o,errors:[],levelPresent:ru(r)}}if(n.parsed===void 0)return{policy:_r(Yt()),errors:n.errors,...n.fallback?{fallback:n.fallback}:{}};return{policy:_r(n.policy),gui:n.policy,errors:n.errors,...n.fallback?{fallback:n.fallback}:{},levelPresent:ru(n.parsed)}}function ru(e){let t=Me(e)&&Me(e.safety)?e.safety:{};return ua.has(t.level)}function FC(e){let t=Object.entries(e),n=new Set(t.flatMap(([r,o])=>o==="on"?[r]:[]));return[...new Set([...[...Do].filter((r)=>!n.has(r)),...t.flatMap(([r,o])=>o==="off"?[r]:[])])]}function _r(e){return{safety:GC(e.safety),worktreeMode:e.workflow.worktree_mode,destructiveCommandProtectionEnabled:e.destructive_command_protection.enabled,destructiveCommandRuleOverrides:e.destructive_command_protection.overrides,destructiveCommandAllowPaths:e.destructive_command_protection.allow_paths,secretProtection:{enabled:e.secret_protection.enabled,disabledRules:FC(e.secret_protection.overrides),denyPaths:e.secret_protection.deny_paths,allowPaths:e.secret_protection.allow_paths}}}function GC(e){let t={...e.overrides.fail_closed!==void 0?{failClosed:e.overrides.fail_closed}:{},...e.overrides.paranoid_rm!==void 0?{paranoidRm:e.overrides.paranoid_rm}:{},...e.overrides.paranoid_interpreters!==void 0?{paranoidInterpreters:e.overrides.paranoid_interpreters}:{}};return{level:e.level,...Object.keys(t).length>0?{overrides:t}:{}}}function mu(e,t){let n=Bd(e,t),r=iu(e,t),o={rules:n.rules,transparentWrappers:n.transparent_wrappers,commandTools:n.command_tools,safety:r.safety,worktreeMode:r.worktreeMode,destructiveCommandProtectionEnabled:r.destructiveCommandProtectionEnabled,destructiveCommandRuleOverrides:r.destructiveCommandRuleOverrides,destructiveCommandAllowPaths:r.destructiveCommandAllowPaths,secretProtection:{enabled:r.secretProtection.enabled??!0,disabledRules:r.secretProtection.disabledRules??[],denyPaths:r.secretProtection.denyPaths,allowPaths:r.secretProtection.allowPaths??[]}},i={...n.userConfig?.overrides,...n.projectConfig?.overrides},s=Object.freeze(Object.fromEntries(o.rules.map((a)=>{let l=n.rulebooks.find((d)=>d.rules.includes(a.name)),c=i[a.name];return[a.name,Object.freeze({id:a.name,...l?{rulebook:Object.freeze({name:l.name,version:l.version}),...UC(l.spec)?{source:l.spec}:{}}:{},...c&&typeof c==="object"?{override:Object.freeze({type:"reason",reason:c.reason})}:{}})]})));return HC(o,zC(n,r),s,r.policyScopes)}function zC(e,t){let n=BC(t);if(e.errors.length===0&&e.warnings.length===0&&!n)return;return{diagnostics:[...e.errors,...e.warnings,...t.errors],reason:jC(e.errors.length>0?$C(e.errors):void 0,e.warnings.length>0?ga(e.warnings.join("; ")):void 0,n)}}function $C(e){return`${ga(e.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function BC(e){if(e.errors.length===0)return;let t=e.fallback==="salvaged"?"the salvaged policy with protective defaults":"built-in protective defaults";return`invalid policy config: ${e.errors.join("; ")}. Enforcing ${t}; the invalid values are not active. Fix the policy file manually`}function UC(e){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(e)}function HC(e,t,n=Object.freeze({}),r){let o=pa(structuredClone(e)),i=r?{policyScopes:pa(structuredClone(r))}:{};if(!t)return Object.freeze({state:"ready",policy:o,diagnostics:Object.freeze([]),ruleMetadata:n,...i});return Object.freeze({state:"degraded",policy:o,diagnostics:Object.freeze([...t.diagnostics]),reason:t.reason,ruleMetadata:n,...i})}function pa(e){if(typeof e!=="object"||e===null)return e;for(let t of Object.values(e))pa(t);return Object.freeze(e)}function jC(...e){return ga(e.filter((t)=>!!t).join("; "))}function ga(e){return/[.!?]$/.test(e)?e:`${e}.`}function $o(e){let t=e.effectiveCapabilities,n=t.fail_closed.enabled,r=t.paranoid_rm.enabled,o=t.paranoid_interpreters.enabled;return{policy:Xd(e.policySnapshot.policy,t),effectiveCapabilities:t,effectiveLevel:ws({failClosed:n,paranoidRm:r,paranoidInterpreters:o}),strict:n,paranoidRm:r,paranoidInterpreters:o,worktreeMode:e.worktreeMode??!1}}import{dirname as AP,isAbsolute as PP,join as yg,parse as TP,resolve as IP,sep as kP}from"path";function xr(e,t){if(e!=="powershell")return t[0]?.provenance==="command-substitution";let n=t[0]?.text==="&"||t[0]?.text==="."?1:0,r=t[n];return r!==void 0&&(r.provenance!=="literal"||n===0&&qC(r))}var VC=/^@(['"])[ \t]*(?:\r\n|[\r\n])/;function In(e,t){let n=VC.exec(e.slice(t)),r=n?.[1];return n&&r?{quote:r,bodyStart:t+n[0].length}:null}function qC(e){return In(e.raw,0)!==null}var KC=/^[A-Za-z_][A-Za-z0-9_]*=/;function Bo(e,t){return e?.provenance==="literal"&&!e.quoted&&e.raw===t&&e.text===t}function Ar(e){let t=Bo(e.words[0],"time")?1:0,n=t===1&&Bo(e.words[t],"-p")?t+1:t,r=t===1&&Bo(e.words[n],"--")?n+1:n,o=Bo(e.words[r],"!")?r+1:r,i=e.words.slice(o).find((s)=>!KC.test(s.text));return i?.provenance==="literal"?i.text:void 0}var Tt=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function Uo(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function Ho(e,t,n){e.push(n),t.reset()}function jo(e){let t=[];return{parts:t,push:(n,r,o)=>{if(r<=n)return;t.push({raw:e.slice(n,r),span:{start:n,end:r},provenance:o})}}}function ha(e){let t=e.parts??[{raw:e.raw,span:e.span,provenance:e.provenance}];return{kind:"word",...e,parts:t}}function kn(e,t,n,r,o,i,s){return ha({text:r,raw:e.slice(t,n),span:{start:t,end:n},provenance:o,quoted:i,...s?{parts:s}:{}})}function ya(e,t,n){if(t>=n||pu(e[t]??""))return null;let r="",o=!1,i=!1,s=t;while(s<n&&!pu(e[s]??"")){let a=e[s]??"";if(a==="'"){o=!0;let l=fu(e,s+1,n,"'");r+=l.text,i||=!l.closed,s=l.next;continue}if(a==='"'){o=!0;let l=fu(e,s+1,n,'"');r+=l.text,i||=!l.closed,s=l.next;continue}if(a==="\\"){o=!0;let l=e[s+1];if(!l||l===`
9
9
  `||l==="\r"){i=!0;break}r+=l,s+=2;continue}if(a==="`"||e.startsWith("$(",s)||e.startsWith("${",s)||e.startsWith("<(",s)||e.startsWith(">(",s))i=!0;r+=a,s++}return{delimiter:r,quoted:o,next:s,ambiguous:i}}function Sa(e,t,n,r){let o=[],i=t;for(let s of r){let a=i,l=!1;while(i<n){let c=YC(e,i,n);if((s.stripTabs?c.text.replace(/^\t+/,""):c.text)===s.delimiter){s.attach({body:s.stripTabs?ZC(e.slice(a,i)):e.slice(a,i),delimiter:s.delimiter,quotedDelimiter:s.quotedDelimiter,bodySpan:{start:a,end:i},terminatorSpan:{start:i,end:c.contentEnd}}),i=c.next,l=!0;break}if(c.next<=i)break;i=c.next}if(l)continue;return o.push({code:"unterminated-heredoc",message:`heredoc delimiter ${s.delimiter} was not found`}),{next:n,issues:o,terminated:!1}}return{next:i,issues:o,terminated:!0}}function fu(e,t,n,r){let o="",i=t;while(i<n&&e[i]!==`
10
10
  `&&e[i]!=="\r"){let s=e[i]??"";if(s===r)return{text:o,next:i+1,closed:!0};if(r==='"'&&s==="\\"&&e[i+1]){let a=e[i+1]??"";o+=["$","`",'"',"\\"].includes(a)?a:`\\${a}`,i+=2;continue}o+=s,i++}return{text:o,next:i,closed:!1}}function pu(e){return e!=="\r"&&(/[\s;&|<>)]/u.test(e)||e==="`")}function YC(e,t,n){let r=t;while(r<n&&e[r]!==`
11
11
  `)r++;let o=r>=n?n:r+1;return{text:e.slice(t,r),contentEnd:r,next:o}}function ZC(e){return e.replace(/(^|\r\n?|\n)\t+/g,"$1")}var Cu=new Set(["&&","||","|","|&"]),XC=new Set(["!","do","elif","else","if","then","until","while"]);function bu(e,t){let n={start:0,end:e.length};if(e.length>t.maxInputLength)return{kind:"program",dialect:"posix",source:e,span:n,status:"limited",issues:[{code:"input-limit",message:`command exceeds ${t.maxInputLength} UTF-16 code units`}],nodes:[]};let r={wordsUsed:0,maxWords:t.maxWords,quotedExpansionEnd:1/0},o=Ko(e,0,e.length,t,r,0),i=[...o.issues,...ab(e,r.quotedExpansionEnd,o.nodes)?[wu]:[],...ib.test(e)?[Ru]:[]];return{kind:"program",dialect:"posix",source:e,span:n,status:Zo(i,o.limited),issues:i,nodes:o.nodes}}function Ko(e,t,n,r,o,i,s){let a=[],l=[],c=Uo(),d=[],u=()=>{if(c.words.length===0&&c.redirections.length===0)return;let m={start:c.start,end:c.end},p=c.words.map((g)=>g.text);Ho(a,c,{kind:"command",dialect:"posix",source:e.slice(m.start,m.end),span:m,words:c.words,redirections:c.redirections,nested:c.nested,displayText:l.length>0&&a.length===0?e.slice(t,n):p.join(" ")})},f=t;while(f<n){let m=e[f];if(!m)break;if(s&&m===s)return u(),Su(a,l),{nodes:a,issues:l,next:f+1,closed:!0,limited:!1,pendingHeredocs:d};if(Tr(m)){if(m.charCodeAt(0)>127)l.push(Ru);if(m===`
@@ -53,6 +53,6 @@ var cs="CC Safety Net could not analyze the command because it exceeds safe anal
53
53
  `).some((n)=>{let r=n.indexOf(t);return r>=0&&/[()[\]{}]/.test(n.slice(r))})}function zI(e,t){return KI.test(e)||t.some((n)=>{let r=qI.get(n.name),o=n.index+n.name.length;return r!==void 0&&!r.test(e.slice(o,o+40))})}function $I(e){return e.some((t)=>dh(t.name).some((n)=>FI.test(n)))}var BI=new Set(["cmd","powershell","pwsh"]);function UI(e,t){let n=yn(e.masked,t),r=oc[e.masked[n]??""];if(r===void 0||r==="}")return!1;let o=e.masked.indexOf(r,n+1),i=e.masked.slice(n+1,o);return o!==-1&&/^\s*,[\w\s,]*$/.test(i)&&/^[,)]/.test(e.masked.slice(yn(e.masked,o+1)))&&!e.literals.some((s)=>s.tokenStart>n&&s.tokenStart<o&&(Ql.has(s.text)||zn(Ee(s.text).toLowerCase())||BI.has(Ee(s.text).toLowerCase().replace(/\.exe$/,""))))}function HI(e){let t=[];return e.split("").map((n,r)=>{let o=t.at(-1)??-1;if(n in oc)t.push(r);if(n===")"||n==="]"||n==="}")t.pop();return o})}function jg(e,t,n,r,o){let i=n[t.tokenStart]??-1,s=e[i]??"",a=sr(e,t.tokenStart),l=yn(e,t.tokenEnd);if(/(?:^|[^\w$])in$|[=!]=$/.test(e.slice(Math.max(0,a-3),a+1)))return!0;if(/^(?:(?:not\s+)?in(?![\w$])|[=!]=)/.test(e.slice(l,l+8)))return!0;if(r&&(s==="["||s==="("))return!1;let c=e[a],d=e[l];if(s==="{"&&c===":")return nk(e,a);let u=(c===s||c===",")&&(d===","||d===oc[s]||s==="{"&&d===":");if(s!=="(")return u&&s!=="";return u&&(o&&VI.test(e.slice(Math.max(0,i-20),i))||(c===","||d===",")&&rk(e,i))}function jI(e,t,n,r){let o=Math.max(0,t.tokenStart-80),i=`${o===0?`
54
54
  `:""}${e.slice(o,t.tokenStart)}`,s=YI.exec(i)?.[1],a=e[n[t.tokenStart]??-1];if(s===void 0||a==="("||a==="[")return!1;let l=yn(e,t.tokenEnd)+1;if(!/^\s*(?:[;\n]|$)/.test(e.slice(t.tokenEnd,l)))return!1;let c=t.tokenStart-i.length+i.lastIndexOf(s);return(r.get(s)??[]).every((d)=>d===c)}var VI=/(?:^|[^\w$.])(?:print|console\s*\.\s*log)\s*$/,qI=new Map([["print",/^\s*\(/],["console",/^\s*\.\s*[\w$]+\s*\(/]]),KI=/(?:^|[^\w$])(?:as|class|const|def|function|import|let|var)\s+(?:print|console)(?![\w$])/,YI=/[;\n{]\s*(?:(?:const|let|var)\s+)?([A-Za-z_$][\w$]*)\s*=\s*$/,ZI=/(?:^|[^\w$.])(?:pathlib\s*\.\s*)?Path\s*$/,XI=/^\s*\.\s*write_(?:text|bytes)\s*\(/,QI=/(?:^|[^\w$.])open\s*$/,JI=/^[bt]*[awx][abtwx]*$/,ek=/(?:^|[^\w$])(?:writeFile|writeFileSync|appendFile|appendFileSync|Bun\s*\.\s*write)\s*$/;function tk(e,t,n){let r=n[t.tokenStart]??-1;if(e.masked[r]!=="(")return!1;let o=sr(e.masked,t.tokenStart),i=yn(e.masked,t.tokenEnd),s=e.masked[i],a=e.masked.slice(Math.max(0,r-40),r);if(ZI.test(a))return(o===r||e.masked[o]===",")&&(s===","||s===")")&&!e.literals.some((c)=>c.tokenStart>r&&c.tokenStart<t.tokenStart)&&XI.test(e.masked.slice(Ei(e.masked,r+1)+1));if(o!==r||s!==",")return!1;if(ek.test(a))return!0;if(!QI.test(a))return!1;let l=e.literals.find((c)=>/^,\s*(?:mode\s*=\s*)?$/.test(e.masked.slice(i,c.tokenStart)));return l!==void 0&&JI.test(l.text)&&/^[,)]/.test(e.masked.slice(yn(e.masked,l.tokenEnd)))}function nk(e,t){let n=sr(e,t),r=/[\w$]*$/.exec(e.slice(Math.max(0,n-63),n+1))?.[0]??"",o=e[sr(e,n+1-r.length)];return o==="{"||o===","}function rk(e,t){let n=sr(e,t),r=e.slice(Math.max(0,n-7),n+1);return!/[\w$)\]]$/.test(r)||LI.test(r)}function ok(e){let t=rc(e);if(t==="python")return"python";if(t==="osascript")return"opaque";return t==="node"||t==="bun"||t==="deno"?"javascript":"simple"}var ik={python:"#",javascript:"/"};function sk(e,t){if(t==="opaque")return{kind:"unmaskable"};let n={masked:e.split(""),literals:[],comments:[]};return ch(e,0,t,n,!1)===null?{kind:"unmaskable"}:{kind:"masked",masked:n.masked.join(""),literals:n.literals,comments:n.comments}}function ch(e,t,n,r,o){let i=0;for(let s=t;s<e.length;s++){let a=e[s]??"";if(o&&a==="}"&&i===0)return s;if(o&&a===ik[n])return null;if(n==="python"&&a==="#"){let g=e.slice(s).search(/[\r\n]/),h=g===-1?e.length:s+g;r.comments.push(e.slice(s,h)),r.masked.fill(" ",s,h),s=h-1;continue}if(a==="{")i++;if(a==="}")i--;if(n==="simple"&&(a==="`"||a==="%"||a==="<")){if(cI.test(e.slice(s)))return null}let l=a==="'"||a==='"'||n==="javascript"&&a==="`"?a:null;if(l===null)continue;if(l==="`"&&dk(e,s))return null;let c=n==="python"?lk(e,s):"",d=n==="python"&&e.startsWith(l.repeat(3),s)?l.repeat(3):l,u=s+d.length,f=l==="`"||/[fF]/.test(c),m=s-c.length,p=f?ak(e,m,u,d,n,r):ck(e,u,d);if(p===null)return null;if(!f){let g=e.slice(u,p);if(n==="simple"&&l==='"'&&dI.test(g))return null;r.literals.push({start:u,text:g,tokenStart:m,tokenEnd:p+d.length}),r.masked.fill(" ",u,p)}r.masked.fill(" ",s,u),r.masked.fill(" ",p,p+d.length),s=p+d.length-1}return o?null:e.length}function ak(e,t,n,r,o,i){let s=o==="python"?"{":"${",a=r==="`"||r.length===3,l="";for(let c=n;c<e.length;c++){let d=e[c]??"";if(e.startsWith(r,c))return i.literals.push({start:n,text:l,tokenStart:t,tokenEnd:c+r.length}),c;if(!a&&(d===`
55
55
  `||d==="\r"))return null;let u=o==="python"&&(d==="{"||d==="}")&&e[c+1]===d;if(!u&&e.startsWith(s,c)){let p=ch(e,c+s.length,o,i,!0);if(p===null)return null;l+=`${s}}`,i.masked.fill(" ",c,c+s.length),i.masked[p]=" ",c=p;continue}let m=d==="\\"&&!(o==="python"&&e[c+1]==="{")||u?2:1;l+=e.slice(c,c+m),i.masked.fill(" ",c,c+m),c+=m-1}return null}function lk(e,t){return lI.exec(e.slice(Math.max(0,t-3),t))?.[1]??""}function ck(e,t,n){let r=n.length===3;for(let o=t;o<e.length;o++){let i=e[o];if(i==="\\"){o++;continue}if(!r&&(i===`
56
- `||i==="\r"))return null;if(e.startsWith(n,o))return o}return null}function dk(e,t){for(let n=t-1;n>=0;n--){let r=e[n];if(!r||/\s/.test(r))continue;return/[\w$\])]/.test(r)}return!1}function uk(e){for(let t of e.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let n=t[0],r=t.index;if(jT.has(n.toLowerCase()))return!0;let o=dh(n);if(!o.some((i)=>VT.has(i)))continue;if(o.length>1)return!0;if(e[sr(e,r)]===".")return!0;if(e[yn(e,r+n.length)]==="(")return!0}return!1}function dh(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((t)=>t.toLowerCase())}function sr(e,t){for(let n=t-1;n>=0;n--)if(!/\s/.test(e[n]??""))return n;return-1}function yn(e,t){for(let n=t;n<e.length;n++)if(!/\s/.test(e[n]??""))return n;return e.length}function mk(e,t,n,r,o,i){return yk(e).flatMap((s)=>{let a=t.getShellSyntax(s);if(a.status==="invalid")return[];return[...lr(a,t,{...n,displayOperandsAreCapturedOutput:!0},r,o,i),...fk(a,r)?pk(a,r).map((l)=>({target:l,cwd:o})):[]]})}function fk(e,t){let n=mi(e);for(let r=0;r<n.length;r++){let o=n[r];if(o?.kind!=="word"||Ee(ht(o.text,t)).toLowerCase()!=="base64")continue;for(let i=r+1;i<n.length;i++){let s=n[i];if(s?.kind==="operator")break;if(s?.kind!=="word")continue;let a=ht(s.text,t);if(a==="--decode"||!a.startsWith("--")&&a.startsWith("-")&&/[dD]/.test(a))return!0}}return!1}function pk(e,t){return mi(e).flatMap((n)=>n.kind==="word"?[ht(n.text,t)]:n.kind==="redirection"&&n.target?[ht(n.target,t)]:[]).flatMap(ic)}function ic(e){let t=hk(e);if(t===null)return[];let n=Buffer.from(t,"base64").toString("utf8");if(n===""||gk(n))return[];return Buffer.from(n,"utf8").toString("base64").replace(/=+$/g,"")===t.replace(/=+$/g,"")?[n]:[]}function gk(e){return Array.from(e).some((t)=>{let n=t.charCodeAt(0);return n<32||n===127})}function hk(e){if(e.length<8||!/^[A-Za-z0-9+/_-]+={0,2}$/.test(e))return null;if(/=/.test(e.replace(/=+$/g,"")))return null;let t=e.replace(/=+$/g,"");if(t.length%4===1)return null;return`${t.replace(/-/g,"+").replace(/_/g,"/")}${"=".repeat((4-t.length%4)%4)}`}function yk(e){let t=[],n={inSingle:!1,inDouble:!1,escaped:!1};for(let r=0;r<e.length;r++){let o=e[r];if(!o)break;if(vr(o,n))continue;if(uh(e,r,n)){let i=Sk(e,r+1);if(i!==null)t.push(i.body),r=i.endIndex;continue}if(!n.inSingle&&o==="`"){let i=Ck(e,r);if(i!==null)t.push(i.body),r=i.endIndex}}return t}function Sk(e,t){let n={inSingle:!1,inDouble:!1,escaped:!1},r=1;for(let o=t+1;o<e.length;o++){let i=e[o];if(!i)break;if(vr(i,n))continue;if(uh(e,o,n)){r++,o++;continue}if(!n.inSingle&&!n.inDouble&&i===")"){if(r--,r===0)return{body:e.slice(t+1,o),endIndex:o}}}return null}function Ck(e,t){let n=!1;for(let r=t+1;r<e.length;r++){let o=e[r];if(!o)break;if(n){n=!1;continue}if(o==="\\"){n=!0;continue}if(o==="`")return{body:e.slice(t+1,r),endIndex:r}}return null}function uh(e,t,n){return!n.inSingle&&e[t]==="$"&&e[t+1]==="("&&e[t+2]!=="("}function bk(e){let t=[],n=[],r=!1,o=!1,i=!1;for(let l=0;l<e.length;l++){let c=e[l];if(c===void 0)break;if(!i&&c==="--"){i=!0;continue}if(i){n.push(c);continue}let d=/^--([^=]+)(?:=(.*))?$/.exec(c);if(d!==null){let u=d[1]??"",f=d[2];if(u===rI)o=!0;if(iI.has(u))r=!0;if(f!==void 0){if(u===Fg)t.push(f);continue}if(aI.has(u)){let m=e[l+1];if(u===Fg&&m!==void 0)t.push(m);l++}continue}if(c.startsWith("-")&&c.length>1){let u=c.slice(1),f="",m="";for(let g=0;g<u.length;g++){let h=u[g]??"";if(oI.has(h))r=!0;if(sI.has(h)){f=h,m=u.slice(g+1);break}}if(f==="")continue;if(m.length>0){if(f===Wg)t.push(m);continue}let p=e[l+1];if(f===Wg&&p!==void 0)t.push(p);l++;continue}n.push(c)}let a=!r&&!o?n.slice(1):n;return[...t,...a]}function vk(e){return e==="env"||e==="command"||e==="builtin"||e==="sudo"}var Ek=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),Vg=".env.",Rk=[".example",".sample",".template",".tpl"],wk=[".env.example.",".env.sample."];function _k(e){let t;try{t=new URL(e.trim())}catch{return!1}return t.protocol!=="file:"&&t.host!==""}function xk(e){return e.length>0&&!/\s/.test(e)}function rs(e,t,n,r){let o=mh(e,t,n,r);return o!==""&&n.paths.entryKind(o)!=="missing"}function mh(e,t,n,r){try{return ao(e,t,n,r)}catch(o){if(o instanceof z)throw o;return""}}var Ak=/[?&][^?&=/]+=/,Pk=new Set(["node_modules","__pycache__"]),Tk=[["vendor","bundle"],["vendor","cache"]];function Ik(e,t,n,r,o){if(_k(e))return null;let i=Ie(e,t,r,o);if(!i)return null;let s=H(i.split("/").pop()??""),a=H(i),l=()=>xk(s)||rs(e,t,r,o),c=H(Lk(e,t,r,o));for(let f of Qs){let m=`~/${f.suffixParts.join("/")}`;if((Kg(a,m)||Kg(c,m))&&Et(f.id,n))return f.id}if(s===".env.defaults"||s.startsWith(Vg)&&Rk.some((f)=>s.endsWith(f))||wk.some((f)=>s.startsWith(f)))return null;let d=kk(i,t,n,r,o);if(d)return d;if(Ek.has(s))return null;for(let f of Xs)if(s===f.basename&&Et(f.id,n))return f.id;if(s.startsWith(Vg)&&Et(ko.id,n)&&l())return ko.id;for(let f of Js)if(s.length>f.prefix.length&&s.startsWith(f.prefix)){let m=s.slice(f.prefix.length)[0];if((m==="-"||m==="_")&&Et(f.id,n)&&l())return f.id}for(let f of ea)if(s.length>f.prefix.length&&s.startsWith(f.prefix)){if(s.slice(f.prefix.length)===f.suffix&&Et(f.id,n))return f.id}if(Mk(a))return null;if(!s.includes(".")&&Er.pattern.test(s)&&Et(Er.id,n))return Er.id;if(Ak.test(e)&&!rs(e,t,r,o))return null;let u=Nk(s,n);if(u)return u;return null}function kk(e,t,n,r,o){return Oo.find((i)=>{if(!Et(i.id,n))return!1;switch(i.id){case"secret.cli.claude-code":return B(e,j(r.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",t,r,o),[".credentials.json"]);case"secret.cli.claude-code.config":{let s=H(e).split("/");return B(e,j(r.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",t,r,o),["settings.json","settings.local.json"])||io(e,"~/.claude.json",t,r,o)||s.at(-2)===".claude"&&["settings.json","settings.local.json"].includes(s.at(-1)??"")||s.at(-1)===".mcp.json"}case"secret.cli.antigravity":return B(e,Ie("~/.gemini/config",t,r,o),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let s=j(r.env.get("CODEX_HOME"),"~/.codex",t,r,o);return B(e,s,["auth.json",".credentials.json"])||or(e,s,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let s=j(r.env.get("CODEX_HOME"),"~/.codex",t,r,o),a=H(e).split("/"),l=a.at(-1)??"";return B(e,s,["config.toml"])||l.endsWith(".config.toml")&&B(e,s,[l])||a.at(-2)===".codex"&&l==="config.toml"}case"secret.cli.gemini":return B(e,oe(j(r.env.get("GEMINI_CLI_HOME"),"~",t,r,o),".gemini"),["oauth_creds.json","mcp-oauth-tokens.json","a2a-oauth-tokens.json","gemini-credentials.json"]);case"secret.cli.gemini.config":{let s=H(e).split("/"),a=r.env.get("GEMINI_CLI_SYSTEM_SETTINGS_PATH"),l=r.env.get("ProgramData")?[oe(j(r.env.get("ProgramData"),"",t,r,o),"gemini-cli")]:[];return B(e,oe(j(r.env.get("GEMINI_CLI_HOME"),"~",t,r,o),".gemini"),["settings.json","google_accounts.json"])||s.at(-1)==="settings.json"&&s.at(-2)===".gemini"||(a?.trim()?io(e,a,t,r,o):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...l].some((c)=>B(e,Ie(c,t,r,o),["settings.json"]))}case"secret.cli.copilot-cli":{let s=j(r.env.get("COPILOT_HOME"),"~/.copilot",t,r,o);return B(e,s,["config.json"])||or(e,s,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return B(e,j(r.env.get("COPILOT_HOME"),"~/.copilot",t,r,o),["mcp-config.json"]);case"secret.cli.kimi-code":{let s=j(r.env.get("KIMI_CODE_HOME"),"~/.kimi-code",t,r,o),a=j(r.env.get("KIMI_SHARE_DIR"),"~/.kimi",t,r,o);return B(e,s,["server.token"])||or(e,s,["credentials"])||or(e,a,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let s=["config.toml","mcp.json"],a=H(e).split("/");return a.at(-1)==="mcp.json"&&a.at(-2)===".kimi-code"||B(e,j(r.env.get("KIMI_CODE_HOME"),"~/.kimi-code",t,r,o),s)||B(e,j(r.env.get("KIMI_SHARE_DIR"),"~/.kimi",t,r,o),[...s,"config.json","config.json.bak"])}case"secret.cli.opencode":{let s=oe(j(r.env.get("XDG_DATA_HOME"),"~/.local/share",t,r,o),"opencode"),a=H(e).split("/").at(-1)??"",l=r.env.get("OPENCODE_DB")?.trim(),c=l&&l!==":memory:"?[l,`${l}-wal`,`${l}-shm`]:[];return B(e,s,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(a)&&B(e,s,[a])||c.some((d)=>io(e,d,t,r,o))}case"secret.cli.opencode.config":{let s=oe(j(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"opencode"),a=r.env.get("ProgramData")?[oe(j(r.env.get("ProgramData"),"",t,r,o),"opencode")]:[],l=["opencode.json","opencode.jsonc"],c=r.env.get("OPENCODE_CONFIG");return l.includes(H(e).split("/").at(-1)??"")||B(e,s,["config.json"])||(c?.trim()?io(e,c,t,r,o):!1)||["/Library/Application Support/opencode","/etc/opencode",...a].some((d)=>B(e,Ie(d,t,r,o),l))}case"secret.cli.pi":return B(e,j(r.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",t,r,o),["auth.json"]);case"secret.cli.pi.config":return B(e,j(r.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",t,r,o),["models.json"]);case"secret.cli.amp":{let s=Ie("~",t,r,o);return[oe(j(r.env.get("XDG_DATA_HOME"),"~/.local/share",t,r,o),"amp"),oe(s,".local","share","amp")].some((l)=>B(e,l,["secrets.json"]))||or(e,oe(s,".amp"),["oauth"])}case"secret.cli.amp.config":{let s=["settings.json","settings.jsonc"],a=[oe(j(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"amp"),oe(Ie("~",t,r,o),".config","amp")],l=H(e).split("/"),c=r.env.get("AMP_SETTINGS_FILE");return a.some((d)=>B(e,d,s))||l.at(-2)===".amp"&&s.includes(l.at(-1)??"")||(c?.trim()?io(e,c,t,r,o):!1)}case"secret.cli.cursor":{let s=oe(j(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"cursor"),a=oe(j(r.env.get("CURSOR_DATA_DIR"),"~/.cursor",t,r,o),"projects");return B(e,Ie("~/.cursor",t,r,o),["auth.json"])||B(e,s,["auth.json"])||H(e).split("/").at(-1)==="mcp-auth.json"&&Sn(H(e),H(a))}case"secret.cli.cursor.config":{let s=H(e).split("/");return s.at(-1)==="mcp.json"&&s.at(-2)===".cursor"}case"secret.cli.grok-build":return B(e,j(r.env.get("GROK_HOME"),"~/.grok",t,r,o),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let s=H(e).split("/");return s.at(-1)==="config.toml"&&s.at(-2)===".grok"||B(e,j(r.env.get("GROK_HOME"),"~/.grok",t,r,o),["config.toml","managed_config.toml","requirements.toml"])||B(e,Ie("/etc/grok",t,r,o),["managed_config.toml","requirements.toml"])}case"secret.cli.droid":return B(e,Ie("~/.factory",t,r,o),["auth.encrypted","auth.v2.file","auth.v2.key","auth.v2.loginkeychain"]);case"secret.cli.droid.config":{let s=H(e).split("/");return s.at(-1)==="mcp.json"&&s.at(-2)===".factory"||B(e,Ie("~/.factory",t,r,o),["settings.json","hooks.json"])}case"secret.cli.devin":return[j(r.env.get("XDG_DATA_HOME"),"~/.local/share",t,r,o),Ie("~/.local/share",t,r,o)].some((s)=>B(e,oe(s,"devin"),["credentials.toml"])||or(e,oe(s,"devin","mcp"),["oauth"]));case"secret.cli.devin.config":return[j(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),Ie("~/.config",t,r,o)].some((s)=>B(e,oe(s,"devin"),["config.json"]));default:return!1}})?.id??null}var qg=new WeakMap;function j(e,t,n,r,o){let i=qg.get(o)??new Map;qg.set(o,i);let s=`${n}\x00${e??""}\x00${t}`,a=i.get(s);if(a!==void 0)return a;let l=Ie(e?.trim()?e:t,n,r,o);return i.set(s,l),l}function B(e,t,n){return n.some((r)=>fh(e,oe(t,r)))}function or(e,t,n){return n.some((r)=>Sn(H(e),H(oe(t,r))))}function io(e,t,n,r,o){return fh(e,Ie(t,n,r,o))}function fh(e,t){return H(e)===H(t)}function oe(e,...t){return Qe([e,...t].filter(Boolean).join("/"))}function Ok(e,t,n,r,o,i){if(n.length===0)return!1;let s=H(ao(e,t,o,i));return n.some((a)=>Sn(s,H(ao(a,r,o,i))))}function Dk(e,t,n,r,o,i){if(n.length===0)return!1;let s=H(ao(e,t,o,i));if(!s)return!1;let a=o.env.get("HOME")??o.home,l=a?Qe(F(pe(a),o.paths,i)):"",c=H(l),d=o.env.get("CC_SAFETY_NET_HOME"),u=H(d?Qe(F(os(pe(d)),o.paths,i)):l&&Qe(F(`${l}/.cc-safety-net`,o.paths,i)));if(u&&Sn(s,u))return!1;return n.some((f)=>{let m=ia(f);if(m&&Yg.basename(s)!==H(m.name))return!1;let p=H(ao(m?.root??f,r,o,i));if(!p)return!1;if(c&&(c===p||c.startsWith(p.endsWith("/")?p:`${p}/`)))return!1;return Sn(s,p)&&!(m&&s===p)})}function Mk(e){let t=e.split("/");return t.some((n)=>Pk.has(n))||Tk.some(([n,r])=>t.some((o,i)=>o===n&&t[i+1]===r))}function Nk(e,t){let n=e.lastIndexOf("."),r=n>0&&n<e.length-1?e.slice(n+1):"";if(r==="")return null;for(let o of ta)if(r===o.extension&&Et(o.id,t))return o.id;for(let o of na)if(o.pattern.test(r)&&Et(o.id,t))return o.id;return null}function H(e){return e.toLowerCase()}function Et(e,t){return!t?.disabledRules?.includes(e)}function Ie(e,t,n,r){let{home:o,normalized:i}=sc(e,n,r);if(!i)return"";if(!o)return i;let s=ac(i,o),a=ts(s)?s:Qe(os(t,s)),l=Qe(F(a,n.paths,r));if(!Sn(l,o)){if(ts(s))return l;return l===a?i:l}let c=l.slice(o.length);return c?`~${c}`:"~"}function Kg(e,t){return e===t||e.startsWith(`${t}/`)}function Lk(e,t,n,r){let{home:o,normalized:i}=sc(e,n,r);if(!i||!o)return"";let s=ac(i,o),a=Yg.normalize(ts(s)?s:Qe(os(t,s))),l=Qe(pe(n.env.get("HOME")??n.home)),c=(f)=>process.platform==="win32"?f.toLowerCase():f,d=[o,l].find((f)=>f!==""&&Sn(c(a),c(f)));if(d===void 0)return"";let u=a.slice(d.length);return u?`~${u}`:"~"}function ao(e,t,n,r){let{home:o,normalized:i}=sc(e,n,r);if(!i)return"";let s=o?ac(i,o):i;return Qe(F(ts(s)?s:os(t,s),n.paths,r))}function sc(e,t,n){let r=t.env.get("HOME")??t.home,o=r?Qe(F(pe(r),t.paths,n)):"",i=Qe(pe(Wk(ht(e,t))));return{home:o,normalized:i}}function Wk(e){if(!e.trim().toLowerCase().startsWith("file:"))return e;try{return FT(e)}catch{return e}}function ac(e,t){if(e==="~")return t;if(e.startsWith("~/"))return oe(t,e.slice(2));return e}function Fk(e){if(process.platform==="win32")return!0;return WT.parse(e).root.length>1}function Qe(e){let t=e.trim(),n=(t.includes("\\")&&Fk(t)?t.replace(/\\/g,"/"):t).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(n==="/")return n;return n.replace(/\/+$/g,"")}function Sn(e,t){return e===t||e.startsWith(t.endsWith("/")?t:`${t}/`)}function Ee(e){return e.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??e}class Cn extends Error{stage;evaluation;name="GuardEvaluationError";constructor(e,t,n){super(`CC Safety Net ${e} dependency failed`,{cause:n});this.stage=e;this.evaluation=t}}var Gk={findPolicyMutation:Mg,findGitMetadataMutation:Fm,resolveGitMetadata:Uk,loadPolicySnapshot:mu,findSensitiveTarget:eh,analyzeCommand:_g,getModes:_s},zk=/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/,$k=["workdir","cwd","working_directory"];function lc(e,t){let n={...Gk,...t.dependencies},r=Vk(e),o=()=>Gt("config-load",r,()=>n.loadPolicySnapshot(t.environment,{...t.policyOptions,cwd:e.context.configCwd})),i=e.route.kind==="unknown"&&r?o():void 0,s=i?.policy.commandTools.find((L)=>L.name===e.toolName),a=s&&r?Bk(e,r,s.cwd,t.environment.paths):e;if("decision"in a)return a;let l=a,c=l===e?{}:{promotedInvocation:l},d=lo(l)?l.command:r,u=Gt("policy-protection",d,()=>Mm(l)),f=$n(u,"input-candidate"),m=$n(u,"declared-command");if(lo(l)&&l.command?.trim()&&m?.program.status==="limited")return{stage:"command-analysis",...c,decision:{kind:"deny",reason:et,ruleId:"analysis.recursion-limit",intent:"stop_and_explain",evidence:{command:l.command,segment:l.command}}};if(f?.program.status==="limited")return{stage:"command-validation",...c,decision:{kind:"deny",reason:Dm,ruleId:"analysis.structural-limit",intent:"stop_and_explain"}};let p=Re(),g=Gt("policy-protection",d,()=>n.resolveGitMetadata([l.context.executionCwd,l.context.configCwd],t.environment)),h=Gt("policy-protection",d,()=>n.findPolicyMutation(u,t.environment,p));if(h){let L=d??h.target;return{stage:"policy-protection",...c,decision:{kind:"deny",reason:Dg,ruleId:"guard.policy-config",intent:"hard_stop",evidence:{command:L,segment:h.target}}}}let S=Gt("policy-protection",d,()=>Tg(u,t.environment,p));if(S){let L=d??S.target;return{stage:"policy-protection",...c,decision:{kind:"deny",reason:Pg,ruleId:"guard.policy-apply",intent:"hard_stop",evidence:{command:L,segment:S.target}}}}let y=Gt("policy-protection",d,()=>n.findGitMetadataMutation(u,g,t.environment,p));if(y){let L=d??y.target;return{stage:"policy-protection",...c,decision:{kind:"deny",reason:be,ruleId:"guard.git-metadata",intent:"hard_stop",evidence:{command:L,segment:y.target}}}}let C=i??o(),v=C.policy,A=n.getModes(v,t.environment.env),P={level:A.effectiveLevel,...Hk(C),...c},I=v.secretProtection.enabled===!1?null:Gt("secret-protection",d,()=>n.findSensitiveTarget(u,v.secretProtection,t.environment,p,{strict:lo(l)||f?.program.dialect==="powershell"?A.strict:void 0}));if(I){let L=d??I.target;return{stage:"secret-protection",...P,decision:{kind:"deny",reason:Zg,intent:"hard_stop",ruleId:I.ruleId,evidence:{command:L,segment:I.target}}}}if(!lo(l))return{stage:"non-command",...P,decision:{kind:"allow"}};if(!l.command||l.command.trim()==="")return{...gh(d),...P};let E=Gt("command-analysis",d,()=>xg(()=>n.analyzeCommand(l.command,{cwd:l.context.configCwd,effectiveCwd:l.context.executionCwd,shell:l.route.shell,policySnapshot:C,environment:t.environment,protectedGitMetadata:g,effectiveCapabilities:A.capabilities,worktreeMode:A.worktreeMode,budget:p,...t.trace?{trace:t.trace}:{}},jk(u),u.store),l.command,t.trace)),G=l.route.shell==="auto"&&u.store.readsAutoAsPowerShell()?()=>{let L=t.trace?.branch(),re={...lc({...l,route:{kind:"command",shell:"posix"}},{...t,...L?{trace:L.trace}:{},dependencies:{...t.dependencies,loadPolicySnapshot:()=>C,resolveGitMetadata:()=>g}}),...c};return{decision:re.decision,withItsTrace:()=>(L?.adopt(),re)}}:void 0;if(E.decision){let L=!A.strict&&(E.decision.ruleId==="raw-text.dangerous-command"||E.decision.reason===rn&&!zk.test(E.decision.evidence?.segment??"")&&Ge(l.command)===null),re=L?G?.():void 0;if(re?.decision.kind==="deny"&&!re.decision.unverifiedByStandardMode)return re.withItsTrace();return{stage:"command-analysis",...P,..."errorCode"in E?{errorCode:E.errorCode}:{},decision:L?{...E.decision,unverifiedByStandardMode:!0}:E.decision}}return G?.().withItsTrace()??{stage:"command-analysis",...P,decision:{kind:"allow"}}}function Bk(e,t,n,r){let o=[...new Set((n?[n]:$k).flatMap((l)=>{let c=Object.getOwnPropertyDescriptor(e.input,l);return c?[c.value]:[]}))],i=o.filter((l)=>typeof l==="string"&&l.trim()!=="");if(o.length>1||i.length!==o.length)return gh(t);let s=i[0],a=s===void 0?e.context.configCwd:po(s,e.context.configCwd,r);if(!a){let l=mr({directory:"requested",problem:"unusable",cwd:s??""});return{stage:"command-validation",decision:{kind:"deny",reason:l.reason,ruleId:l.ruleId,intent:l.intent,evidence:{command:t,segment:t}}}}return hr(e.toolName,e.input,{kind:"command",shell:"auto"},{configCwd:e.context.configCwd,executionCwd:a},t)}function Uk(e,t){let n=[...new Set(e.filter((r)=>typeof r==="string"&&r!==""))].flatMap((r)=>t.gitMetadata(r)??[]);if(n.length===0)return null;return Object.freeze({entries:Object.freeze([...new Set(n.flatMap((r)=>r.entries))]),markerFiles:Object.freeze([...new Set(n.flatMap((r)=>r.markerFiles))]),directories:Object.freeze([...new Set(n.flatMap((r)=>r.directories))]),hooksDirectories:Object.freeze([...new Set(n.flatMap((r)=>r.hooksDirectories))])})}function Hk(e){if(e.state==="ready")return{};return{configFallback:{reason:e.reason}}}function jk(e){return $n(e,"declared-command")?.program}function Vk(e){try{return gr(e.input)}catch(t){let n=lo(e)?e.command:void 0;throw new Cn("policy-protection",ph("policy-protection",t instanceof lt?void 0:n,t),t)}}function Gt(e,t,n){try{return n()}catch(r){throw new Cn(e,ph(e,r instanceof lt?void 0:t,r),r)}}function ph(e,t,n){let r=n instanceof on?{reason:rt,ruleId:"analysis.strict-unparseable"}:n instanceof z||n instanceof qe?{reason:cs,ruleId:"analysis.limit"}:{reason:cr,ruleId:"analysis.failed-closed"};return{stage:e,decision:{kind:"deny",...r,intent:"stop_and_explain",...t?{evidence:{command:t,segment:t}}:{}}}}function gh(e){let t=ur();return{stage:"command-validation",decision:{kind:"deny",reason:t.reason,ruleId:t.ruleId,intent:t.intent,...e?{evidence:{command:e,segment:e}}:{}}}}function lo(e){return e.route.kind==="command"}import{appendFileSync as iO,mkdirSync as sO}from"fs";import{isAbsolute as aO,join as uc}from"path";import{lstatSync as yh,readdirSync as qk,readFileSync as Kk,rmdirSync as Yk,statSync as Sh,unlinkSync as Zk,utimesSync as Xk,writeFileSync as Qk}from"fs";import{join as co}from"path";function hh(e,t={}){return zo(Vt(e,t),e.home).policy.audit.retention_days}var dc=86400000,Jk=".last-prune",eO=/^\d{4}-\d{2}$/,tO=/^((\d{4}-\d{2})-\d{2})-.+\.jsonl$/,Ch=(e)=>Math.floor(e/dc);function vh(e,t,n=()=>new Date){try{let r=n().getTime();if(!Sh(t,{throwIfNoEntry:!1})?.isDirectory())return;let o=co(t,Jk),i=Sh(o,{throwIfNoEntry:!1})?.mtimeMs;if(i!==void 0&&Ch(i)===Ch(r))return;let s=r-hh(e)*dc,a=new Date(r).toISOString().slice(0,7);for(let l of cc(t)){if(l.isDirectory()){nO(co(t,l.name),s,a);continue}if(l.isFile()&&l.name.endsWith(".jsonl"))rO(co(t,l.name),s)}Qk(o,"",{mode:384}),Xk(o,r/1000,r/1000)}catch{}}function nO(e,t,n){for(let r of cc(e)){if(!r.isDirectory()||!eO.test(r.name))continue;let o=co(e,r.name);for(let i of cc(o)){if(!i.isFile())continue;let s=tO.exec(i.name);if(!s||s[2]!==r.name)continue;let a=Date.parse(`${s[1]}T00:00:00.000Z`)+dc;if(!Number.isFinite(a)||a>=t)continue;Eh(co(o,i.name))}if(r.name!==n)bh(o)}bh(e)}function rO(e,t){try{let n=yh(e);if(n.mtimeMs>=t)return;let r=Kk(e,"utf-8").split(`
57
- `).filter((o)=>o.trim()).map(oO);if(r.length===0)return;if(r.some((o)=>o===void 0||o>=t))return;if(yh(e).mtimeMs!==n.mtimeMs)return;Eh(e)}catch{}}function oO(e){try{let t=JSON.parse(e).ts,n=typeof t==="string"?Date.parse(t):Number.NaN;return Number.isFinite(n)?n:void 0}catch{return}}function cc(e){try{return qk(e,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function Eh(e){try{Zk(e)}catch{}}function bh(e){try{Yk(e)}catch{}}var lO="2.7.4",cO=1e4,dO=2000,uO=256,mO=32768;function fO(e){let t=e.trim();if(!t)return null;let n=t.replace(/[^A-Za-z0-9_.-]+/g,"_");if(n=n.replace(/^[._-]+|[._-]+$/g,"").slice(0,128),!n||n==="."||n==="..")return null;return n}function pO(e){return(e??"").replace(/[^A-Za-z0-9]/g,"-").slice(0,180)||"no-cwd"}function mc(e,t,n,r,o,i,s={}){let a=fO(t);if(!a)return;let l=hO(e);if(!l)return;try{let c=(s.now??(()=>new Date))().toISOString(),d=is(wt(n),s.failureStage?Number.POSITIVE_INFINITY:cO),u=is(wt(r),dO),f=s.toolName?is(wt(s.toolName),uO):void 0,m=i===null?void 0:is(wt(i),mO),p=uc(l,pO(m?.value??null),c.slice(0,7));sO(p,{recursive:!0,mode:448});let g=uc(p,`${c.slice(0,10)}-${a}.jsonl`),h={ts:c,id:(s.createId??xs)(),v:lO,sessionId:a,decision:s.decision??"deny",agent:s.agent,shape:s.shape,level:s.level,configFallback:s.configFallback,toolName:f?.value,command:d.value,segment:u.value,...d.truncated||u.truncated||f?.truncated||m?.truncated?{truncated:!0}:{},reason:o,ruleId:s.ruleId,intent:s.intent,failureStage:s.failureStage,errorCode:s.errorCode,cwd:m?.value??null};iO(g,`${JSON.stringify(h)}
56
+ `||i==="\r"))return null;if(e.startsWith(n,o))return o}return null}function dk(e,t){for(let n=t-1;n>=0;n--){let r=e[n];if(!r||/\s/.test(r))continue;return/[\w$\])]/.test(r)}return!1}function uk(e){for(let t of e.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let n=t[0],r=t.index;if(jT.has(n.toLowerCase()))return!0;let o=dh(n);if(!o.some((i)=>VT.has(i)))continue;if(o.length>1)return!0;if(e[sr(e,r)]===".")return!0;if(e[yn(e,r+n.length)]==="(")return!0}return!1}function dh(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_$\s]+/).map((t)=>t.toLowerCase())}function sr(e,t){for(let n=t-1;n>=0;n--)if(!/\s/.test(e[n]??""))return n;return-1}function yn(e,t){for(let n=t;n<e.length;n++)if(!/\s/.test(e[n]??""))return n;return e.length}function mk(e,t,n,r,o,i){return yk(e).flatMap((s)=>{let a=t.getShellSyntax(s);if(a.status==="invalid")return[];return[...lr(a,t,{...n,displayOperandsAreCapturedOutput:!0},r,o,i),...fk(a,r)?pk(a,r).map((l)=>({target:l,cwd:o})):[]]})}function fk(e,t){let n=mi(e);for(let r=0;r<n.length;r++){let o=n[r];if(o?.kind!=="word"||Ee(ht(o.text,t)).toLowerCase()!=="base64")continue;for(let i=r+1;i<n.length;i++){let s=n[i];if(s?.kind==="operator")break;if(s?.kind!=="word")continue;let a=ht(s.text,t);if(a==="--decode"||!a.startsWith("--")&&a.startsWith("-")&&/[dD]/.test(a))return!0}}return!1}function pk(e,t){return mi(e).flatMap((n)=>n.kind==="word"?[ht(n.text,t)]:n.kind==="redirection"&&n.target?[ht(n.target,t)]:[]).flatMap(ic)}function ic(e){let t=hk(e);if(t===null)return[];let n=Buffer.from(t,"base64").toString("utf8");if(n===""||gk(n))return[];return Buffer.from(n,"utf8").toString("base64").replace(/=+$/g,"")===t.replace(/=+$/g,"")?[n]:[]}function gk(e){return Array.from(e).some((t)=>{let n=t.charCodeAt(0);return n<32||n===127})}function hk(e){if(e.length<8||!/^[A-Za-z0-9+/_-]+={0,2}$/.test(e))return null;if(/=/.test(e.replace(/=+$/g,"")))return null;let t=e.replace(/=+$/g,"");if(t.length%4===1)return null;return`${t.replace(/-/g,"+").replace(/_/g,"/")}${"=".repeat((4-t.length%4)%4)}`}function yk(e){let t=[],n={inSingle:!1,inDouble:!1,escaped:!1};for(let r=0;r<e.length;r++){let o=e[r];if(!o)break;if(vr(o,n))continue;if(uh(e,r,n)){let i=Sk(e,r+1);if(i!==null)t.push(i.body),r=i.endIndex;continue}if(!n.inSingle&&o==="`"){let i=Ck(e,r);if(i!==null)t.push(i.body),r=i.endIndex}}return t}function Sk(e,t){let n={inSingle:!1,inDouble:!1,escaped:!1},r=1;for(let o=t+1;o<e.length;o++){let i=e[o];if(!i)break;if(vr(i,n))continue;if(uh(e,o,n)){r++,o++;continue}if(!n.inSingle&&!n.inDouble&&i===")"){if(r--,r===0)return{body:e.slice(t+1,o),endIndex:o}}}return null}function Ck(e,t){let n=!1;for(let r=t+1;r<e.length;r++){let o=e[r];if(!o)break;if(n){n=!1;continue}if(o==="\\"){n=!0;continue}if(o==="`")return{body:e.slice(t+1,r),endIndex:r}}return null}function uh(e,t,n){return!n.inSingle&&e[t]==="$"&&e[t+1]==="("&&e[t+2]!=="("}function bk(e){let t=[],n=[],r=!1,o=!1,i=!1;for(let l=0;l<e.length;l++){let c=e[l];if(c===void 0)break;if(!i&&c==="--"){i=!0;continue}if(i){n.push(c);continue}let d=/^--([^=]+)(?:=(.*))?$/.exec(c);if(d!==null){let u=d[1]??"",f=d[2];if(u===rI)o=!0;if(iI.has(u))r=!0;if(f!==void 0){if(u===Fg)t.push(f);continue}if(aI.has(u)){let m=e[l+1];if(u===Fg&&m!==void 0)t.push(m);l++}continue}if(c.startsWith("-")&&c.length>1){let u=c.slice(1),f="",m="";for(let g=0;g<u.length;g++){let h=u[g]??"";if(oI.has(h))r=!0;if(sI.has(h)){f=h,m=u.slice(g+1);break}}if(f==="")continue;if(m.length>0){if(f===Wg)t.push(m);continue}let p=e[l+1];if(f===Wg&&p!==void 0)t.push(p);l++;continue}n.push(c)}let a=!r&&!o?n.slice(1):n;return[...t,...a]}function vk(e){return e==="env"||e==="command"||e==="builtin"||e==="sudo"}var Ek=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),Vg=".env.",Rk=[".example",".sample",".template",".tpl"],wk=[".env.example.",".env.sample."];function _k(e){let t;try{t=new URL(e.trim())}catch{return!1}return t.protocol!=="file:"&&t.host!==""}function xk(e){return e.length>0&&!/\s/.test(e)}function rs(e,t,n,r){let o=mh(e,t,n,r);return o!==""&&n.paths.entryKind(o)!=="missing"}function mh(e,t,n,r){try{return ao(e,t,n,r)}catch(o){if(o instanceof z)throw o;return""}}var Ak=/[?&][^?&=/]+=/,Pk=new Set(["node_modules","__pycache__"]),Tk=[["vendor","bundle"],["vendor","cache"]];function Ik(e,t,n,r,o){if(_k(e))return null;let i=Ie(e,t,r,o);if(!i)return null;let s=H(i.split("/").pop()??""),a=H(i),l=()=>xk(s)||rs(e,t,r,o),c=H(Lk(e,t,r,o));for(let f of Qs){let m=`~/${f.suffixParts.join("/")}`;if((Kg(a,m)||Kg(c,m))&&Et(f.id,n))return f.id}if(s===".env.defaults"||s.startsWith(Vg)&&Rk.some((f)=>s.endsWith(f))||wk.some((f)=>s.startsWith(f)))return null;let d=kk(i,t,n,r,o);if(d)return d;if(Ek.has(s))return null;for(let f of Xs)if(s===f.basename&&Et(f.id,n))return f.id;if(s.startsWith(Vg)&&Et(ko.id,n)&&l())return ko.id;for(let f of Js)if(s.length>f.prefix.length&&s.startsWith(f.prefix)){let m=s.slice(f.prefix.length)[0];if((m==="-"||m==="_")&&Et(f.id,n)&&l())return f.id}for(let f of ea)if(s.length>f.prefix.length&&s.startsWith(f.prefix)){if(s.slice(f.prefix.length)===f.suffix&&Et(f.id,n))return f.id}if(Mk(a))return null;if(!s.includes(".")&&Er.pattern.test(s)&&Et(Er.id,n))return Er.id;if(Ak.test(e)&&!rs(e,t,r,o))return null;let u=Nk(s,n);if(u)return u;return null}function kk(e,t,n,r,o){return Oo.find((i)=>{if(!Et(i.id,n))return!1;switch(i.id){case"secret.cli.claude-code":return B(e,j(r.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",t,r,o),[".credentials.json"]);case"secret.cli.claude-code.config":{let s=H(e).split("/");return B(e,j(r.env.get("CLAUDE_CONFIG_DIR"),"~/.claude",t,r,o),["settings.json","settings.local.json"])||io(e,"~/.claude.json",t,r,o)||s.at(-2)===".claude"&&["settings.json","settings.local.json"].includes(s.at(-1)??"")||s.at(-1)===".mcp.json"}case"secret.cli.antigravity":return B(e,Ie("~/.gemini/config",t,r,o),["hooks.json","mcp_config.json"]);case"secret.cli.codex":{let s=j(r.env.get("CODEX_HOME"),"~/.codex",t,r,o);return B(e,s,["auth.json",".credentials.json"])||or(e,s,["secrets",".sandbox-secrets"])}case"secret.cli.codex.config":{let s=j(r.env.get("CODEX_HOME"),"~/.codex",t,r,o),a=H(e).split("/"),l=a.at(-1)??"";return B(e,s,["config.toml"])||l.endsWith(".config.toml")&&B(e,s,[l])||a.at(-2)===".codex"&&l==="config.toml"}case"secret.cli.gemini":return B(e,oe(j(r.env.get("GEMINI_CLI_HOME"),"~",t,r,o),".gemini"),["oauth_creds.json","mcp-oauth-tokens.json","a2a-oauth-tokens.json","gemini-credentials.json"]);case"secret.cli.gemini.config":{let s=H(e).split("/"),a=r.env.get("GEMINI_CLI_SYSTEM_SETTINGS_PATH"),l=r.env.get("ProgramData")?[oe(j(r.env.get("ProgramData"),"",t,r,o),"gemini-cli")]:[];return B(e,oe(j(r.env.get("GEMINI_CLI_HOME"),"~",t,r,o),".gemini"),["settings.json","google_accounts.json"])||s.at(-1)==="settings.json"&&s.at(-2)===".gemini"||(a?.trim()?io(e,a,t,r,o):!1)||["/Library/Application Support/GeminiCli","/etc/gemini-cli",...l].some((c)=>B(e,Ie(c,t,r,o),["settings.json"]))}case"secret.cli.copilot-cli":{let s=j(r.env.get("COPILOT_HOME"),"~/.copilot",t,r,o);return B(e,s,["config.json"])||or(e,s,["mcp-oauth-config","mcp-secrets"])}case"secret.cli.copilot-cli.config":return B(e,j(r.env.get("COPILOT_HOME"),"~/.copilot",t,r,o),["mcp-config.json"]);case"secret.cli.kimi-code":{let s=j(r.env.get("KIMI_CODE_HOME"),"~/.kimi-code",t,r,o),a=j(r.env.get("KIMI_SHARE_DIR"),"~/.kimi",t,r,o);return B(e,s,["server.token"])||or(e,s,["credentials"])||or(e,a,["credentials","mcp-oauth"])}case"secret.cli.kimi-code.config":{let s=["config.toml","mcp.json"],a=H(e).split("/");return a.at(-1)==="mcp.json"&&a.at(-2)===".kimi-code"||B(e,j(r.env.get("KIMI_CODE_HOME"),"~/.kimi-code",t,r,o),s)||B(e,j(r.env.get("KIMI_SHARE_DIR"),"~/.kimi",t,r,o),[...s,"config.json","config.json.bak"])}case"secret.cli.opencode":{let s=oe(j(r.env.get("XDG_DATA_HOME"),"~/.local/share",t,r,o),"opencode"),a=H(e).split("/").at(-1)??"",l=r.env.get("OPENCODE_DB")?.trim(),c=l&&l!==":memory:"?[l,`${l}-wal`,`${l}-shm`]:[];return B(e,s,["auth.json","mcp-auth.json"])||/^opencode(-.+)?\.db(-wal|-shm)?$/.test(a)&&B(e,s,[a])||c.some((d)=>io(e,d,t,r,o))}case"secret.cli.opencode.config":{let s=oe(j(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"opencode"),a=r.env.get("ProgramData")?[oe(j(r.env.get("ProgramData"),"",t,r,o),"opencode")]:[],l=["opencode.json","opencode.jsonc"],c=r.env.get("OPENCODE_CONFIG");return l.includes(H(e).split("/").at(-1)??"")||B(e,s,["config.json"])||(c?.trim()?io(e,c,t,r,o):!1)||["/Library/Application Support/opencode","/etc/opencode",...a].some((d)=>B(e,Ie(d,t,r,o),l))}case"secret.cli.pi":return B(e,j(r.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",t,r,o),["auth.json"]);case"secret.cli.pi.config":return B(e,j(r.env.get("PI_CODING_AGENT_DIR"),"~/.pi/agent",t,r,o),["models.json"]);case"secret.cli.amp":{let s=Ie("~",t,r,o);return[oe(j(r.env.get("XDG_DATA_HOME"),"~/.local/share",t,r,o),"amp"),oe(s,".local","share","amp")].some((l)=>B(e,l,["secrets.json"]))||or(e,oe(s,".amp"),["oauth"])}case"secret.cli.amp.config":{let s=["settings.json","settings.jsonc"],a=[oe(j(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"amp"),oe(Ie("~",t,r,o),".config","amp")],l=H(e).split("/"),c=r.env.get("AMP_SETTINGS_FILE");return a.some((d)=>B(e,d,s))||l.at(-2)===".amp"&&s.includes(l.at(-1)??"")||(c?.trim()?io(e,c,t,r,o):!1)}case"secret.cli.cursor":{let s=oe(j(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),"cursor"),a=oe(j(r.env.get("CURSOR_DATA_DIR"),"~/.cursor",t,r,o),"projects");return B(e,Ie("~/.cursor",t,r,o),["auth.json"])||B(e,s,["auth.json"])||H(e).split("/").at(-1)==="mcp-auth.json"&&Sn(H(e),H(a))}case"secret.cli.cursor.config":{let s=H(e).split("/");return s.at(-1)==="mcp.json"&&s.at(-2)===".cursor"}case"secret.cli.grok-build":return B(e,j(r.env.get("GROK_HOME"),"~/.grok",t,r,o),["auth.json","mcp_credentials.json"]);case"secret.cli.grok-build.config":{let s=H(e).split("/");return s.at(-1)==="config.toml"&&s.at(-2)===".grok"||B(e,j(r.env.get("GROK_HOME"),"~/.grok",t,r,o),["config.toml","managed_config.toml","requirements.toml"])||B(e,Ie("/etc/grok",t,r,o),["managed_config.toml","requirements.toml"])}case"secret.cli.droid":return B(e,Ie("~/.factory",t,r,o),["auth.encrypted","auth.v2.file","auth.v2.key","auth.v2.loginkeychain"]);case"secret.cli.droid.config":{let s=H(e).split("/");return s.at(-1)==="mcp.json"&&s.at(-2)===".factory"||B(e,Ie("~/.factory",t,r,o),["settings.json","hooks.json"])}case"secret.cli.devin":return[j(r.env.get("XDG_DATA_HOME"),"~/.local/share",t,r,o),Ie("~/.local/share",t,r,o)].some((s)=>B(e,oe(s,"devin"),["credentials.toml"])||or(e,oe(s,"devin","mcp"),["oauth"]));case"secret.cli.devin.config":return[j(r.env.get("XDG_CONFIG_HOME"),"~/.config",t,r,o),Ie("~/.config",t,r,o)].some((s)=>B(e,oe(s,"devin"),["config.json"]));default:return!1}})?.id??null}var qg=new WeakMap;function j(e,t,n,r,o){let i=qg.get(o)??new Map;qg.set(o,i);let s=`${n}\x00${e??""}\x00${t}`,a=i.get(s);if(a!==void 0)return a;let l=Ie(e?.trim()?e:t,n,r,o);return i.set(s,l),l}function B(e,t,n){return n.some((r)=>fh(e,oe(t,r)))}function or(e,t,n){return n.some((r)=>Sn(H(e),H(oe(t,r))))}function io(e,t,n,r,o){return fh(e,Ie(t,n,r,o))}function fh(e,t){return H(e)===H(t)}function oe(e,...t){return Qe([e,...t].filter(Boolean).join("/"))}function Ok(e,t,n,r,o,i){if(n.length===0)return!1;let s=H(ao(e,t,o,i));return n.some((a)=>Sn(s,H(ao(a,r,o,i))))}function Dk(e,t,n,r,o,i){if(n.length===0)return!1;let s=H(ao(e,t,o,i));if(!s)return!1;let a=o.env.get("HOME")??o.home,l=a?Qe(F(pe(a),o.paths,i)):"",c=H(l),d=o.env.get("CC_SAFETY_NET_HOME"),u=H(d?Qe(F(os(pe(d)),o.paths,i)):l&&Qe(F(`${l}/.cc-safety-net`,o.paths,i)));if(u&&Sn(s,u))return!1;return n.some((f)=>{let m=ia(f);if(m&&Yg.basename(s)!==H(m.name))return!1;let p=H(ao(m?.root??f,r,o,i));if(!p)return!1;if(c&&(c===p||c.startsWith(p.endsWith("/")?p:`${p}/`)))return!1;return Sn(s,p)&&!(m&&s===p)})}function Mk(e){let t=e.split("/");return t.some((n)=>Pk.has(n))||Tk.some(([n,r])=>t.some((o,i)=>o===n&&t[i+1]===r))}function Nk(e,t){let n=e.lastIndexOf("."),r=n>0&&n<e.length-1?e.slice(n+1):"";if(r==="")return null;for(let o of ta)if(r===o.extension&&Et(o.id,t))return o.id;for(let o of na)if(o.pattern.test(r)&&Et(o.id,t))return o.id;return null}function H(e){return e.toLowerCase()}function Et(e,t){return!t?.disabledRules?.includes(e)}function Ie(e,t,n,r){let{home:o,normalized:i}=sc(e,n,r);if(!i)return"";if(!o)return i;let s=ac(i,o),a=ts(s)?s:Qe(os(t,s)),l=Qe(F(a,n.paths,r));if(!Sn(l,o)){if(ts(s))return l;return l===a?i:l}let c=l.slice(o.length);return c?`~${c}`:"~"}function Kg(e,t){return e===t||e.startsWith(`${t}/`)}function Lk(e,t,n,r){let{home:o,normalized:i}=sc(e,n,r);if(!i||!o)return"";let s=ac(i,o),a=Yg.normalize(ts(s)?s:Qe(os(t,s))),l=Qe(pe(n.env.get("HOME")??n.home)),c=(f)=>process.platform==="win32"?f.toLowerCase():f,d=[o,l].find((f)=>f!==""&&Sn(c(a),c(f)));if(d===void 0)return"";let u=a.slice(d.length);return u?`~${u}`:"~"}function ao(e,t,n,r){let{home:o,normalized:i}=sc(e,n,r);if(!i)return"";let s=o?ac(i,o):i;return Qe(F(ts(s)?s:os(t,s),n.paths,r))}function sc(e,t,n){let r=t.env.get("HOME")??t.home,o=r?Qe(F(pe(r),t.paths,n)):"",i=Qe(pe(Wk(ht(e,t))));return{home:o,normalized:i}}function Wk(e){if(!e.trim().toLowerCase().startsWith("file:"))return e;try{return FT(e)}catch{return e}}function ac(e,t){if(e==="~")return t;if(e.startsWith("~/"))return oe(t,e.slice(2));return e}function Fk(e){if(process.platform==="win32")return!0;return WT.parse(e).root.length>1}function Qe(e){let t=e.trim(),n=(t.includes("\\")&&Fk(t)?t.replace(/\\/g,"/"):t).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(n==="/")return n;return n.replace(/\/+$/g,"")}function Sn(e,t){return e===t||e.startsWith(t.endsWith("/")?t:`${t}/`)}function Ee(e){return e.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??e}class Cn extends Error{stage;evaluation;name="GuardEvaluationError";constructor(e,t,n){super(`CC Safety Net ${e} dependency failed`,{cause:n});this.stage=e;this.evaluation=t}}var Gk={findPolicyMutation:Mg,findGitMetadataMutation:Fm,resolveGitMetadata:Uk,loadPolicySnapshot:mu,findSensitiveTarget:eh,analyzeCommand:_g,getModes:_s},zk=/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/,$k=["workdir","cwd","working_directory"];function lc(e,t){let n={...Gk,...t.dependencies},r=Vk(e),o=()=>Gt("config-load",r,()=>n.loadPolicySnapshot(t.environment,{...t.policyOptions,cwd:e.context.configCwd})),i=e.route.kind==="unknown"&&r?o():void 0,s=i?.policy.commandTools.find((L)=>L.name===e.toolName),a=s&&r?Bk(e,r,s.cwd,t.environment.paths):e;if("decision"in a)return a;let l=a,c=l===e?{}:{promotedInvocation:l},d=lo(l)?l.command:r,u=Gt("policy-protection",d,()=>Mm(l)),f=$n(u,"input-candidate"),m=$n(u,"declared-command");if(lo(l)&&l.command?.trim()&&m?.program.status==="limited")return{stage:"command-analysis",...c,decision:{kind:"deny",reason:et,ruleId:"analysis.recursion-limit",intent:"stop_and_explain",evidence:{command:l.command,segment:l.command}}};if(f?.program.status==="limited")return{stage:"command-validation",...c,decision:{kind:"deny",reason:Dm,ruleId:"analysis.structural-limit",intent:"stop_and_explain"}};let p=Re(),g=Gt("policy-protection",d,()=>n.resolveGitMetadata([l.context.executionCwd,l.context.configCwd],t.environment)),h=Gt("policy-protection",d,()=>n.findPolicyMutation(u,t.environment,p));if(h){let L=d??h.target;return{stage:"policy-protection",...c,decision:{kind:"deny",reason:Dg,ruleId:"guard.policy-config",intent:"hard_stop",evidence:{command:L,segment:h.target}}}}let S=Gt("policy-protection",d,()=>Tg(u,t.environment,p));if(S){let L=d??S.target;return{stage:"policy-protection",...c,decision:{kind:"deny",reason:Pg,ruleId:"guard.policy-apply",intent:"hard_stop",evidence:{command:L,segment:S.target}}}}let y=Gt("policy-protection",d,()=>n.findGitMetadataMutation(u,g,t.environment,p));if(y){let L=d??y.target;return{stage:"policy-protection",...c,decision:{kind:"deny",reason:be,ruleId:"guard.git-metadata",intent:"hard_stop",evidence:{command:L,segment:y.target}}}}let C=i??o(),v=C.policy,A=n.getModes(v,t.environment.env),P={level:A.effectiveLevel,...Hk(C),...c},I=v.secretProtection.enabled===!1?null:Gt("secret-protection",d,()=>n.findSensitiveTarget(u,v.secretProtection,t.environment,p,{strict:lo(l)||f?.program.dialect==="powershell"?A.strict:void 0}));if(I){let L=d??I.target;return{stage:"secret-protection",...P,decision:{kind:"deny",reason:Zg,intent:"hard_stop",ruleId:I.ruleId,evidence:{command:L,segment:I.target}}}}if(!lo(l))return{stage:"non-command",...P,decision:{kind:"allow"}};if(!l.command||l.command.trim()==="")return{...gh(d),...P};let E=Gt("command-analysis",d,()=>xg(()=>n.analyzeCommand(l.command,{cwd:l.context.configCwd,effectiveCwd:l.context.executionCwd,shell:l.route.shell,policySnapshot:C,environment:t.environment,protectedGitMetadata:g,effectiveCapabilities:A.capabilities,worktreeMode:A.worktreeMode,budget:p,...t.trace?{trace:t.trace}:{}},jk(u),u.store),l.command,t.trace)),G=l.route.shell==="auto"&&u.store.readsAutoAsPowerShell()?()=>{let L=t.trace?.branch(),re={...lc({...l,route:{kind:"command",shell:"posix"}},{...t,...L?{trace:L.trace}:{},dependencies:{...t.dependencies,loadPolicySnapshot:()=>C,resolveGitMetadata:()=>g}}),...c};return{decision:re.decision,withItsTrace:()=>(L?.adopt(),re)}}:void 0;if(E.decision){let L=!A.strict&&(E.decision.ruleId==="raw-text.dangerous-command"||E.decision.reason===rn&&!zk.test(E.decision.evidence?.segment??"")&&Ge(l.command)===null),re=L?G?.():void 0;if(re?.decision.kind==="deny"&&!re.decision.unverifiedByStandardMode)return re.withItsTrace();return{stage:"command-analysis",...P,..."errorCode"in E?{errorCode:E.errorCode}:{},decision:L?{...E.decision,unverifiedByStandardMode:!0}:E.decision}}return G?.().withItsTrace()??{stage:"command-analysis",...P,decision:{kind:"allow"}}}function Bk(e,t,n,r){let i=[...new Set((n===!1?[]:n?[n]:$k).flatMap((c)=>{let d=Object.getOwnPropertyDescriptor(e.input,c);return d?[d.value]:[]}))],s=i.filter((c)=>typeof c==="string"&&c.trim()!=="");if(i.length>1||s.length!==i.length)return gh(t);let a=s[0],l=a===void 0?e.context.configCwd:po(a,e.context.configCwd,r);if(!l){let c=mr({directory:"requested",problem:"unusable",cwd:a??""});return{stage:"command-validation",decision:{kind:"deny",reason:c.reason,ruleId:c.ruleId,intent:c.intent,evidence:{command:t,segment:t}}}}return hr(e.toolName,e.input,{kind:"command",shell:"auto"},{configCwd:e.context.configCwd,executionCwd:l},t)}function Uk(e,t){let n=[...new Set(e.filter((r)=>typeof r==="string"&&r!==""))].flatMap((r)=>t.gitMetadata(r)??[]);if(n.length===0)return null;return Object.freeze({entries:Object.freeze([...new Set(n.flatMap((r)=>r.entries))]),markerFiles:Object.freeze([...new Set(n.flatMap((r)=>r.markerFiles))]),directories:Object.freeze([...new Set(n.flatMap((r)=>r.directories))]),hooksDirectories:Object.freeze([...new Set(n.flatMap((r)=>r.hooksDirectories))])})}function Hk(e){if(e.state==="ready")return{};return{configFallback:{reason:e.reason}}}function jk(e){return $n(e,"declared-command")?.program}function Vk(e){try{return gr(e.input)}catch(t){let n=lo(e)?e.command:void 0;throw new Cn("policy-protection",ph("policy-protection",t instanceof lt?void 0:n,t),t)}}function Gt(e,t,n){try{return n()}catch(r){throw new Cn(e,ph(e,r instanceof lt?void 0:t,r),r)}}function ph(e,t,n){let r=n instanceof on?{reason:rt,ruleId:"analysis.strict-unparseable"}:n instanceof z||n instanceof qe?{reason:cs,ruleId:"analysis.limit"}:{reason:cr,ruleId:"analysis.failed-closed"};return{stage:e,decision:{kind:"deny",...r,intent:"stop_and_explain",...t?{evidence:{command:t,segment:t}}:{}}}}function gh(e){let t=ur();return{stage:"command-validation",decision:{kind:"deny",reason:t.reason,ruleId:t.ruleId,intent:t.intent,...e?{evidence:{command:e,segment:e}}:{}}}}function lo(e){return e.route.kind==="command"}import{appendFileSync as iO,mkdirSync as sO}from"fs";import{isAbsolute as aO,join as uc}from"path";import{lstatSync as yh,readdirSync as qk,readFileSync as Kk,rmdirSync as Yk,statSync as Sh,unlinkSync as Zk,utimesSync as Xk,writeFileSync as Qk}from"fs";import{join as co}from"path";function hh(e,t={}){return zo(Vt(e,t),e.home).policy.audit.retention_days}var dc=86400000,Jk=".last-prune",eO=/^\d{4}-\d{2}$/,tO=/^((\d{4}-\d{2})-\d{2})-.+\.jsonl$/,Ch=(e)=>Math.floor(e/dc);function vh(e,t,n=()=>new Date){try{let r=n().getTime();if(!Sh(t,{throwIfNoEntry:!1})?.isDirectory())return;let o=co(t,Jk),i=Sh(o,{throwIfNoEntry:!1})?.mtimeMs;if(i!==void 0&&Ch(i)===Ch(r))return;let s=r-hh(e)*dc,a=new Date(r).toISOString().slice(0,7);for(let l of cc(t)){if(l.isDirectory()){nO(co(t,l.name),s,a);continue}if(l.isFile()&&l.name.endsWith(".jsonl"))rO(co(t,l.name),s)}Qk(o,"",{mode:384}),Xk(o,r/1000,r/1000)}catch{}}function nO(e,t,n){for(let r of cc(e)){if(!r.isDirectory()||!eO.test(r.name))continue;let o=co(e,r.name);for(let i of cc(o)){if(!i.isFile())continue;let s=tO.exec(i.name);if(!s||s[2]!==r.name)continue;let a=Date.parse(`${s[1]}T00:00:00.000Z`)+dc;if(!Number.isFinite(a)||a>=t)continue;Eh(co(o,i.name))}if(r.name!==n)bh(o)}bh(e)}function rO(e,t){try{let n=yh(e);if(n.mtimeMs>=t)return;let r=Kk(e,"utf-8").split(`
57
+ `).filter((o)=>o.trim()).map(oO);if(r.length===0)return;if(r.some((o)=>o===void 0||o>=t))return;if(yh(e).mtimeMs!==n.mtimeMs)return;Eh(e)}catch{}}function oO(e){try{let t=JSON.parse(e).ts,n=typeof t==="string"?Date.parse(t):Number.NaN;return Number.isFinite(n)?n:void 0}catch{return}}function cc(e){try{return qk(e,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function Eh(e){try{Zk(e)}catch{}}function bh(e){try{Yk(e)}catch{}}var lO="2.7.5",cO=1e4,dO=2000,uO=256,mO=32768;function fO(e){let t=e.trim();if(!t)return null;let n=t.replace(/[^A-Za-z0-9_.-]+/g,"_");if(n=n.replace(/^[._-]+|[._-]+$/g,"").slice(0,128),!n||n==="."||n==="..")return null;return n}function pO(e){return(e??"").replace(/[^A-Za-z0-9]/g,"-").slice(0,180)||"no-cwd"}function mc(e,t,n,r,o,i,s={}){let a=fO(t);if(!a)return;let l=hO(e);if(!l)return;try{let c=(s.now??(()=>new Date))().toISOString(),d=is(wt(n),s.failureStage?Number.POSITIVE_INFINITY:cO),u=is(wt(r),dO),f=s.toolName?is(wt(s.toolName),uO):void 0,m=i===null?void 0:is(wt(i),mO),p=uc(l,pO(m?.value??null),c.slice(0,7));sO(p,{recursive:!0,mode:448});let g=uc(p,`${c.slice(0,10)}-${a}.jsonl`),h={ts:c,id:(s.createId??xs)(),v:lO,sessionId:a,decision:s.decision??"deny",agent:s.agent,shape:s.shape,level:s.level,configFallback:s.configFallback,toolName:f?.value,command:d.value,segment:u.value,...d.truncated||u.truncated||f?.truncated||m?.truncated?{truncated:!0}:{},reason:o,ruleId:s.ruleId,intent:s.intent,failureStage:s.failureStage,errorCode:s.errorCode,cwd:m?.value??null};iO(g,`${JSON.stringify(h)}
58
58
  `,{encoding:"utf-8",mode:384}),vh(e,l,s.now)}catch{}}function is(e,t){return{value:e.slice(0,t),truncated:e.length>t}}function gO(e){let t=e.env.get("CC_SAFETY_NET_AUDIT_HOME");if(e.env.get("NODE_ENV")==="test"&&!t)return null;let n=t||e.home;return n&&aO(n)?n:null}function hO(e){let t=gO(e);return t?uc(t,".cc-safety-net","logs"):null}function wh(e,t,n,r=!0,o){if(t.decision.kind==="allow"){if(!n||e.route.kind!=="command")return;let a=Rh(e);return{decision:"allow",command:a,segment:a,reason:"allowed",cwd:e.context.executionCwd,toolName:e.toolName,level:t.level,...t.configFallback?{configFallback:!0}:{}}}let i=t.decision.evidence,s=i?.command??(r?Rh(e):"");return{decision:"deny",command:s,segment:i?.segment??s,reason:t.decision.reason,cwd:e.context.executionCwd,toolName:e.toolName,level:t.level,...t.configFallback?{configFallback:!0}:{},ruleId:t.decision.ruleId,intent:t.decision.intent,failureStage:o?.stage,errorCode:o?.errorCode}}function Rh(e){return"command"in e?e.command??"":""}function _h(e,t,n,r){if(!t)return;let o;try{o=n()}catch{return}if(typeof o!=="string"||!o.trim())return;mc(e,o,t.command,t.segment,t.reason,t.cwd,{decision:t.decision,agent:r.agent,shape:r.shape,level:t.level,configFallback:t.configFallback,toolName:t.toolName,ruleId:t.ruleId,intent:t.intent,failureStage:t.failureStage,errorCode:t.errorCode})}function xh(e,t,n,r){let o;try{o=n()}catch{return}if(typeof o!=="string"||!o.trim())return;mc(e,o,t.command??"",t.segment??t.command??"",t.reason,r.cwd??null,{decision:"deny",agent:r.agent,shape:r.shape,toolName:r.toolName??t.toolName,ruleId:t.ruleId,intent:t.intent})}function Ph(e,t,n){try{let r=lc(t,{environment:e,...n.guard});return Ah(e,t,r,n),r}catch(r){if(!(r instanceof Cn))throw r;throw Ah(e,t,r.evaluation,n,!(r.cause instanceof lt),{stage:r.stage,errorCode:yO(r.cause)}),r}}function Ah(e,t,n,r,o=!0,i){_h(e,wh(n.promotedInvocation??t,n,r.guard?.auditAllowed??!1,o,i),r.audit.getSessionId,{agent:r.audit.agent,shape:r.audit.shape})}function yO(e){if(e instanceof z)return K[e.kind].errorCode;if(e instanceof lt)return"tool-input-limit";if(e instanceof qe)return"structural-shell-syntax-limit";if(e instanceof on)return"unparseable-command";return"unexpected-error"}function ss(e,t={}){return{malformed:!0,denial:ur(t),cwd:e}}function as(e,t={}){return{malformed:!0,denial:dr(t),cwd:e}}function fc(e,t){return{malformed:!0,denial:mr(e,t),cwd:e.cwd}}function Th(e,t={}){return(n,r)=>{try{return SO(n,r,e,t)}catch(o){return console.error("CC Safety Net error:",o),e.block(dr())}}}function SO(e,t,n,r){let o=ed();if(n.cancelled?.(t))return n.block(dr());let i=n.extract(e,t,o.paths);if(!i)return n.allow;let s=()=>n.getSessionId(e,t);if("malformed"in i)return xh(o,i.denial,s,{agent:n.agent,toolName:i.denial.toolName,cwd:i.cwd}),n.block(i.denial);let a=(l,c)=>{let d=hc(l,{includeEvidence:c});return d?n.block(d):n.allow};try{let l=Ph(o,i,{guard:{auditAllowed:od(o.env),policyOptions:r.policyOptions,dependencies:r.guardDependencies},audit:{agent:n.agent,getSessionId:s}});return a(l,!0)}catch(l){if(!(l instanceof Cn))throw l;if(dt(J.debug,o.env))console.error(`CC Safety Net debug: ${n.debugLabel} analysis failed: ${Sc(l.cause)}`);return a(l.evaluation,n.includeEvidenceOnError(i))}}var CO={agent:"amp",debugLabel:"amp tool.call",extract:(e,t,n)=>vO(e,t,n),getSessionId:(e)=>wO(e),allow:{action:"allow"},block:(e)=>_O(e),includeEvidenceOnError:(e)=>e.route.kind==="command"},Ih=bO();function bO(e={}){return Th(CO,e)}function vO(e,t,n){if(!e||typeof e!=="object")return as(null);let r=e;if(typeof r.tool!=="string"||r.tool.trim()==="")return ss(null);if(!r.input||typeof r.input!=="object")return ss(null,{toolName:r.tool});let o=EO(t);if(!o)return as(null,{toolName:r.tool});let i=$c(".",[o],n);if(!i)return fc({directory:"session",problem:"unusable",cwd:o},{toolName:r.tool});let s=RO(t,e);if(!s.ok)return as(i,{toolName:r.tool});if(!s.command)return hr(r.tool,r.input,{kind:fs(r.tool)},{configCwd:i,executionCwd:i},null);if(typeof s.command.command!=="string"||s.command.command.trim()==="")return ss(i,{toolName:r.tool});let a=typeof s.command.dir==="string"?s.command.dir:".",l=po(a,i,n);if(!l)return fc({directory:"requested",problem:"unusable",cwd:a},{command:s.command.command,toolName:r.tool});return hr(r.tool,r.input,{kind:"command",shell:"posix"},{configCwd:i,executionCwd:l},s.command.command)}function EO(e){let t=e.system.workspaceRoot;if(!t)return;try{let n=e.helpers.filePathFromURI(t);return typeof n==="string"&&n.trim()!==""?n:void 0}catch{return}}function RO(e,t){try{return{ok:!0,command:e.helpers.shellCommandFromToolCall(t)}}catch{return{ok:!1}}}function wO(e){if(!e||typeof e!=="object")return;let t=e.thread?.id;return typeof t==="string"&&t.trim()!==""?t:void 0}function _O(e){return{action:"reject-and-continue",message:yc(e)}}function xO(e){e.on("tool.call",(t)=>Ih(t,e))}export{xO as default};