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.
- package/dist/amp/cc-safety-net/index.ts +4 -4
- package/dist/api.js +1 -1
- package/dist/bin/hook.js +44 -44
- package/dist/chunks/{index-gyftnsm3.js → index-a1hayde0.js} +2 -2
- package/dist/chunks/index-dm4v8s9a.js +54 -0
- package/dist/chunks/index-edtb8nxp.js +2 -0
- package/dist/chunks/index-eg9by26f.js +2 -0
- package/dist/chunks/{index-xmyz6zt1.js → index-kzz5h21y.js} +1 -1
- package/dist/chunks/index-r6tk9ysc.js +4 -0
- package/dist/cli.js +101 -101
- package/dist/deepseek-harness/index.js +1 -1
- package/dist/index.js +4 -4
- package/dist/openclaw/cc-safety-net/index.js +4 -4
- package/dist/openclaw/cc-safety-net/openclaw.plugin.json +1 -1
- package/dist/openclaw/cc-safety-net/package.json +1 -1
- package/dist/pi/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunks/index-1zvxgg5q.js +0 -4
- package/dist/chunks/index-affgnv6y.js +0 -2
- package/dist/chunks/index-bt5yemsj.js +0 -2
- package/dist/chunks/index-k92nxp12.js +0 -54
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// cc-safety-net managed OpenClaw plugin. Do not edit. Reinstall with: npx -y cc-safety-net install --openclaw
|
|
2
|
-
// version: 2.7.
|
|
2
|
+
// version: 2.7.5
|
|
3
3
|
var hc={id:"cc-safety-net",name:"CC Safety Net",description:"Block destructive commands and secret-file access before OpenClaw runs a tool."};var ls="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 as={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."},vn={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,...as},processedCandidateBytes:{cap:4194304,...as},pathEnvironmentExpansion:{cap:64,...as},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,...vn},trackedHeredocFiles:{cap:64,...vn},scriptFiles:{cap:64,...vn},controlFlowStates:{cap:64,...vn},wrapperPeelIterations:{cap:20,...vn},derivedCommandShape:vn});class z extends Error{kind;name="AnalysisLimit";constructor(e){super(K[e].reason);this.kind=e}}function we(){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 Oh=[/\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 Rt(e){return Dh(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 Dh(e){return Oh.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 Mh={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 Nh(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.":Mh[e.intent??"manual_only"]].filter((o)=>o!==void 0).join(`
|
|
4
4
|
|
|
5
5
|
`)}function yc(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 Lh={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{...Lh[e.directory][e.problem],command:t.command,toolName:t.toolName,cwd:e.cwd}}function Cc(e){return Nh({...e,redact:Rt})}function Sc(e){return Rt(e instanceof Error?e.message:String(e))}import{isAbsolute as ys,relative as dy,resolve as zc,sep as uy}from"node:path";import{basename as vc,dirname as Wh,isAbsolute as Fh,join as Gh,normalize as zh,resolve as bc}from"node:path";var $h=256,uo=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 lt(e,t=process.platform){if(t!=="win32")return!1;return(e[0]==="/"||e[0]==="\\")&&(e[1]==="/"||e[1]==="\\")}function ms(e,t){return cs(e,0,t)}function cs(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=ds(e,o+2),l=Bh(e,o,t);if(l===null){if(uo.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+=Uh(c,t,n),o=l+1;continue}let s=ds(e,o+1);if(!s){r+="$",o++;continue}r+=us(s,n)??`$${s}`,o+=s.length+1}return r}function Bh(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 Uh(e,t,n){let r=e.slice(2,-1),o=ds(r,0);if(!o)return e;let i=r.slice(o.length);if(!i)return us(o,n)??e;let s=[":-",":+",":=",":?","-","+","=","?"].find((c)=>i.startsWith(c));if(!s){if(uo.has(o))throw new z("pathEnvironmentExpansion");return e}if(!uo.has(o))return e;if(s.endsWith("="))throw new z("pathEnvironmentExpansion");let a=us(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??"":cs(i.slice(s.length),t+1,n);return l?cs(i.slice(s.length),t+1,n):""}function ds(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 us(e,t){if(!uo.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 Ec(n,e,s,o);let a=Wh(i);if(a===i||o.length>=$h)return Ec(n,e,i,o);o.push(vc(i)),i=a}}function Ec(e,t,n,r){let o=r.length===0?n:Gh(n,...r.reverse());return e.resolvedPaths.set(t,o),o}function Hh(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=_c(e,t,n);if(!o)return"";return F(o,n.paths,r).replace(/\\/g,"/")}function Rc(e,t,n,r,o){let i=_c(e,t,n);if(!i)return null;if(o(vc(i)))return F(i,n.paths,r).replace(/\\/g,"/");let s=Hh(i,n.paths,r);return s===null?null:s.replace(/\\/g,"/")}function _c(e,t,n){let r=n.home,o=ms(e.trim(),n).replace(/\\/g,"/");if(!o)return"";let i=o==="~"?r:o.startsWith("~/")?bc(r,o.slice(2)):o,s=pe(i);return zh(Fh(s)?s:bc(t,s))}import{types as jh}from"node:util";var Vh=new Set(["find","findbyname","glob","grep","grepsearch","listdir","listpermissions","ls","read","readfile","readurlcontent","searchweb","view","viewfile"]),qh=new Set(["command","diff","input","patch","patchtext"]),xc=new TextEncoder,Kh=new TextDecoder,Yh=/\s/,Zh=64;class ct 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 Xh(e){return e.replace(/[-_\s]/g,"").toLowerCase()}function fo(e){return Vh.has(Xh(e))}function gr(e){if(!e||typeof e!=="object")return;Wc(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 kc(e,t){return Oc(e,t,!1,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1)}function Oc(e,t,n,r,o){let i=Lc(e,r,o);if(typeof e==="string")return n?[e]:[];if(!i)return[];let s=i.entries.flatMap(([a,l])=>Oc(l,t,i.array?n:t.has(Dc(a)),r,o+1));return r.ancestors.delete(i.object),s}function Dc(e){return e.replace(/-/g,"_").toLowerCase()}function Mc(e){return Nc(e,!0,{nodes:0,keys:0,stringBytes:0,ancestors:new Set},1).flatMap(Jh)}function Nc(e,t,n,r){let o=Lc(e,n,r);if(typeof e==="string")return t?[e]:[];if(!o)return[];let i=o.entries.flatMap(([s,a])=>Nc(a,o.array?t:qh.has(Dc(s)),n,r+1));return n.ancestors.delete(o.object),i}function Qh(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 Lc(e,t,n){if(Qh(e,t,n),!e||typeof e!=="object")return null;let r=Wc(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 Wc(e){if(jh.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 ct}function Jh(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=ey(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(...fs(c));continue}if(o)continue;if(c.startsWith("diff --git ")){t.push(...fs(c));continue}if(c.startsWith("--- ")){let d=n[l+1]??"";if(!d.startsWith("+++ "))continue;t.push(...gs(mo(c.slice(4),!0),mo(d.slice(4),!0))),l++;continue}if(!r)t.push(...fs(c))}return t}function ey(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 fs(e){let t=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(e);if(t?.[1])return Ic(t[1]);let n=/^\*\*\* Move to: (.+)$/.exec(e);if(n?.[1])return Ic(n[1]);if(e.startsWith("diff --git "))return ty(e.slice(11));let r=/^--- (.+)$/.exec(e);if(r?.[1])return Tc(r[1]);let o=/^\+\+\+ (.+)$/.exec(e);if(o?.[1])return Tc(o[1]);let i=/^(?:rename|copy) (?:from|to) (.+)$/.exec(e);if(i?.[1])return ly(i[1]);return[]}function ty(e){let t=ny(e);if(t.length===2&&t[0]&&t[1])return gs(t[0],t[1]);let n=ry(e);return n?gs(e.slice(n.oldStart,n.oldEnd),e.slice(n.newStart,n.newEnd)):[]}function ny(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=Fc(e,n,r);if(!o)return[];t.push(o.value),n=o.end}while($t(e[n]))n++;return n===e.length?t:[]}function ry(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>Zh)tt();if(oy(e,t,i,o,n))return{oldStart:t,oldEnd:i,newStart:o,newEnd:n}}return null}function oy(e,t,n,r,o){if(ps(e,t,n,r,o))return!0;let i=Ac(e,"/",t,n),s=Ac(e,"/",r,o);if(i<=t||s<=r)return!1;if(ps(e,t,i,r,s))return!1;return ps(e,i+1,n,s+1,o)}function ps(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 Ac(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&&Yh.test(e)}function Fc(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:Kh.decode(Uint8Array.from(r)),end:o+1};if(i!=="\\"||n==="'"){r.push(...xc.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(...xc.encode(iy(s[0]??""))),o+=2}return null}function iy(e){return{a:"\x07",b:"\b",f:"\f",n:`
|
|
6
6
|
`,r:"\r",t:"\t",v:"\v"}[e]??e}function sy(e){return pr(cy(e))}function gs(e,t){if(e==="/dev/null")return Pc(t);if(t==="/dev/null")return Pc(e);if(e.startsWith("a/")&&t.startsWith("b/"))return[e.slice(2),t.slice(2)].flatMap(pr);let n=ay(e,t)??(e===t?Gc(e):null);return[e,t,...n?[n]:[]].flatMap(pr)}function Pc(e){let t=Gc(e);return[e,...t?[t]:[]].flatMap(pr)}function Gc(e){let t=e.indexOf("/");return t>0&&t<e.length-1?e.slice(t+1):null}function ay(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 Tc(e){return sy(mo(e,!0))}function ly(e){return pr(mo(e,!1))}function mo(e,t){let n=e.trim(),r=n[0]==='"'||n[0]==="'"?n[0]:void 0;if(r){let o=Fc(n,0,r);if(o&&(t||n.slice(o.end).trim()===""))return o.value}return t?n.split("\t",1)[0]?.trim()??"":n}function cy(e){return e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function pr(e){return e===""||e==="/dev/null"?[]:[e]}function Ic(e){let t=e.split("\t",1)[0]?.trim().replace(/^['"]|['"]$/g,"")??"";return t===""||t==="/dev/null"?[]:[t]}function Cs(e,t,n){if(lt(e))return;let r=t.flatMap((i)=>hs(i,n));if(!r[0])return;let o=hs(ys(e)?e:zc(r[0],e),n)[0];if(!o)return;return r.some((i)=>my(o,i))?o:void 0}function Ss(e,t,n){if(lt(e))return;return hs(ys(e)?e:zc(t,e),n)[0]}function $c(e,t,n){return Ss(e,t,n)?"outside-workspace":"unusable"}function hs(e,t){let n=t.realpath(e);if(n===null)return[];return t.isDirectory(n)?[n]:[]}function my(e,t){let n=dy(t,e);return n===""||n!==".."&&!n.startsWith(`..${uy}`)&&!ys(n)}function po(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 Gy}from"node:child_process";import{lstatSync as zy,realpathSync as $y,statSync as By}from"node:fs";import{isAbsolute as Uy}from"node:path";import{homedir as Hy,tmpdir as jy}from"node:os";import{statSync as Ly}from"node:fs";import{join as Wy}from"node:path";import{spawnSync as fy}from"node:child_process";import{accessSync as Bc,constants as Uc,existsSync as hr,lstatSync as py,opendirSync as gy,readFileSync as yr,realpathSync as wn,statSync as Rn}from"node:fs";import{dirname as Vc,isAbsolute as bs,join as We,resolve as go}from"node:path";var hy=["/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"],yy=5000;function qc(e,t=Oy(),n=yy){let r=Cy(e),o=r===null?null:Sy(r);if(r===null||o===null)return null;let i=Iy(r,o,t,n);return i===null?null:{recursiveSubmodules:i}}function Cy(e){try{let t=wn(go(e));return Rn(t).isDirectory()?t:null}catch{return null}}function Sy(e){let t=Ty(e);if(!t)return null;try{let n=py(t);if(n.isSymbolicLink()||!n.isFile())return null;let r=Es(t);if(!r?.commonDir)return null;if(!vy(r.gitDir,t))return null;return Zc(r.gitDir,r.commonDir)?null:{gitDir:r.gitDir,commonDir:r.commonDir}}catch{return null}}function Es(e){try{let t=by(e);if(!t)return null;let n=wn(bs(t)?t:go(Vc(e),t));if(!Rn(n).isDirectory())return null;return{gitDir:n,commonDir:Ey(n)}}catch{return null}}function by(e){let t=yr(e,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";if(!t.startsWith("gitdir:"))return null;return t.slice(7).trim()||null}function Ey(e){try{let t=yr(We(e,"commondir"),"utf-8").split(/\r?\n/,1)[0]?.trim();if(!t)return null;let n=wn(bs(t)?t:go(e,t));return Rn(n).isDirectory()?n:null}catch{return null}}function vy(e,t){let n=wy(e);return n===null?!1:Ry(e,n,t)}function wy(e){let t=We(e,"gitdir");if(!hr(t))return null;let n=yr(t,"utf-8").split(/\r?\n/,1)[0]?.trim()??"";return n===""?null:n}function Ry(e,t,n){try{return _y(bs(t)?t:go(e,t),n)}catch{return!1}}function _y(e,t){try{let n=Rn(e),r=Rn(t);if(n.ino!==0&&r.ino!==0&&n.dev===r.dev&&n.ino===r.ino)return!0}catch{}return Hc(wn.native(e))===Hc(wn.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 hr(We(e,"commondir"))||Zc(e,e)}function Zc(e,t){return[We(t,"config"),We(e,"config.worktree")].some(xy)||Py(e)}var jc=1048576;function Xc(e){let t=Rn(e);if(!t.isFile()||t.size>jc)throw Error(`${e} is not a regular file within ${jc} bytes`);return yr(e,"utf-8")}function xy(e){try{return/(?:^|[\s\]])worktree\s*=/i.test(Xc(e))}catch(t){return t.code!=="ENOENT"}}var Ay=1e4;function Py(e){let t=[e],n=0;try{while(t.length>0){let r=t.pop(),o=gy(r);try{for(let i=o.readSync();i!==null;i=o.readSync()){if(n++,i.isSymbolicLink()||i.isFIFO()||n>Ay)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 Ty(e){try{return vs(wn(e))}catch{return null}}function vs(e){let t=e;while(!0){let n=We(t,".git");if(hr(n))return n;let r=Vc(t);if(r===t)return null;t=r}}function Iy(e,t,n,r){if(ky(t))return!0;if(n===null)return!0;let o=fy(n,["config","--get","submodule.recurse"],{cwd:e,encoding:"utf8",env:Dy(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 ky(e){return[We(e.commonDir,"config"),We(e.gitDir,"config.worktree")].filter((t)=>hr(t)).some((t)=>My(t))}function Oy(){return hy.find((e)=>hr(e))??null}function Cr(e){return e==="GIT_CONFIG_COUNT"||e==="GIT_CONFIG_PARAMETERS"||/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(e)}function Dy(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!Cr(t)))}function My(e){let t;try{t=yr(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(Ny(n)&&l==="path")return!0;if(n==="submodule"&&l==="recurse")r=Qc(c)}return r}function Ny(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=we(),r=vs(ge(e,e,t,n)),o=r?Fy(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 Fy(e,t,n,r){try{let o=ge(e,t,n,r),i=Ly(e),s=i.isFile()?o:null,a=i.isFile()?Es(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(Wy(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 Vy={realpath:(e)=>{try{let t=$y(e);return Uy(t)?t:null}catch{return null}},entryKind:(e)=>{try{let t=zy(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 By(e).isDirectory()}catch{return!1}}};function ed(){let e=new Map;return Ky({env:new Map(Object.entries(process.env).flatMap(([t,n])=>n===void 0?[]:[[t,n]])),home:pe(process.env.HOME||Hy()),tmpdir:jy(),darwinUserTempDir:()=>ho(e,"",qy),paths:Vy})}function qy(){if(process.platform!=="darwin")return null;let e=Gy("/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 Ky(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"}},Co=["standard","strict","paranoid"];function td(e,t){if(!t)return e;return Co.indexOf(t)>Co.indexOf(e)?t:e}function nd(e){let t=So(J.level,e);return Co.find((n)=>n===t)}function rd(e,t){return td(e,nd(t))}function Yy(e){let t=So(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 ${Co.join(", ")}.`);return}function Zy(e){if(e===void 0||e==="all")return"all";if(e==="blocked")return"blocked";return"invalid"}function od(e){return Zy(So(J.auditScope,e))==="all"}function Rs(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=Yy(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:Rs(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"?ws(e,t):So(e,t);return n==="1"||n?.toLowerCase()==="true"}function ws(e,t){return t.get(e)}function So(e,t){let n=ws(e.name,t);if(n!==void 0)return n;if(e.legacyName)return ws(e.legacyName,t);return}import{dirname as To}from"node:path";import{closeSync as Xy,constants as id,fstatSync as Qy,fsyncSync as cD,lstatSync as Ps,mkdirSync as dD,openSync as Jy,readdirSync as uD,readFileSync as eC,realpathSync as Ts,renameSync as mD,rmdirSync as fD,statSync as tC,unlinkSync as pD,writeFileSync as gD}from"node:fs";import{isAbsolute as sd,join as Is,normalize as nC,parse as As,relative as ks,resolve as Os,sep as Ds}from"node:path";function xs(){let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0");return`${e()}${e()}`}var rC=Symbol("PolicyFilesystemScope"),oC=Symbol("PolicyFilesystemTarget"),iC=id.O_NOFOLLOW??0;class he extends Error{name="PolicyFilesystemError";constructor(e){super(`Unable to access ${e} filesystem safely.`)}}function Bt(e,t){return{[rC]:!0,root:Os(e),label:t}}function ad(e,t){let n=nC(t);if(t===""||sd(t)||n===".."||n.startsWith(`..${Ds}`))throw new he(e.label);return{[oC]:!0,scope:e,relativePath:n,path:Is(e.root,n)}}function Sr(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 Eo(e){return dd(e.scope.label,()=>{if(!bo(e))return null;let t=Jy(e.path,id.O_RDONLY|iC);return sC(t,()=>{let n=Qy(t);if(!n.isFile())throw new he(e.scope.label);let r=eC(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 sC(e,t){try{return t()}finally{Xy(e)}}function bo(e,t="file"){let n=aC(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);lC(n,Ts(i),e.scope.label)}return!0}function aC(e){if(!Ps(e.root,{throwIfNoEntry:!1}))return null;if(!tC(e.root).isDirectory())throw new he(e.label);return Ts(e.root)}function lC(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 fC,join as jt,relative as pC,resolve as _t,sep as gC}from"node: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 cC=/^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/,dC=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),uC="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),SD=new RegExp(`^${dC}/(${Ut.source.slice(1,-1)})/${uC}$`);function mC(e){return`.cc-safety-net/rules/${e}/rulebook.json`}function pd(e){if(vo(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||!cC.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:mC(o),name:o}}function vo(e){return fd.test(e)}var gd="rule.json",wo="policy.json",hd=".cc-safety-net",hC="rules",yC="CC_SAFETY_NET_HOME",yd="`cc-safety-net rule update`";function CC(e){return _t(e,md)}function SC(e){return jt(CC(e),gd)}function An(e){return jt(_t(e),hd,wo)}function Ns(e,t={}){return t.userConfigDir??(t.userConfigPath?Ht(t.userConfigPath):jt(bC(e),hC))}function bC(e){let t=e.env.get(yC);return t?_t(pe(t)):jt(e.home,hd)}function EC(e,t={}){return jt(Ns(e,t),gd)}function Vt(e,t={}){return jt(Ht(Ns(e,t)),wo)}function Cd(e,t){let n=we();return F(An(t.cwd),e.paths,n)===F(_t(Vt(e,t)),e.paths,n)}function Sd(e,t){let n=t.userConfigPath??EC(e,t),r=t.projectConfigPath??SC(t.cwd),o=vC(e,t),i=wC(r,t.cwd);return{userConfigPath:n,projectConfigPath:r,userScope:o,projectScope:i,userConfigTarget:Sr(o,n),projectConfigTarget:Sr(i,r)}}function vC(e,t){let n=t.userConfigPath?Ht(Ht(_t(t.userConfigPath))):Ht(_t(t.userConfigDir??Ns(e,t)));return Bt(n,"user policy")}function wC(e,t){let n=_t(t),r=_t(e),o=pC(n,r);if(o!==".."&&!o.startsWith(`..${gC}`)&&!fC(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"]),Ed=new Set(["python","python3","python2","node","ruby","perl"]),Ro=/^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 vd="Rulebook exceeds CC Safety Net's safe validation limits.",wd="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 Rd(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 Re(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 RC={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(!RC[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 br(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 _C(e))br(n,t);return t.inSingle||t.inDouble}function _C(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===`
|
|
7
|
-
`||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);br(s,n)}return t}var Bs=new Set(["rm","find","rsync","xargs","parallel"]),xC=new Set(["git","busybox",...Bs,...Q,...Ed,...Fe]),AC=new Set(["python","node","ruby","perl"]);function _d(e){let t=N(e);return xC.has(t)||De(t)}function De(e){return AC.has(PC(e))}function PC(e){let t=k(e).toLowerCase();return Ro.test(t)?"python":t}function js(e){try{let t=Eo(TC(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=DC(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 TC(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(", ")}`,IC=/^[^/]+\/[^/]+$/,kC=["version","rules","overrides","transparent_wrappers","command_tools"],OC=/^[^\s\p{Cc}]{1,256}$/u,Us="non-empty, at most 256 characters, no whitespace or control characters";function DC(e){let t=MC(e);return{errors:qs(HC(t,kC,(n)=>n.kind==="custom"),": "," "),sources:UC(e,t)}}function MC(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")],...NC(e.rules,t),...FC(e.overrides),...zC(e.transparent_wrappers),...t?[]:WC(e.rules),...qt(e.overrides)?Object.keys(e.overrides).filter((n)=>!IC.test(n)).map((n)=>se(["overrides",n],"must use <rulebook-name>/<rule-name>")):[],...$C(e.transparent_wrappers),...BC(e.command_tools)]}function NC(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"),...LC(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 LC(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 WC(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 FC(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[...GC(n.reason,["overrides",t,"reason"]),...n.intent===void 0||Ys(n.intent)?[]:[T(["overrides",t,"intent"],Vs)]]})}function GC(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 zC(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 $C(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 BC(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"&&OC.test(e)}function UC(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 HC(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=qC(e);if(t.errors.length>0)throw Error(t.errors.join("; "));return e}var jC=`required non-empty string up to ${At} characters`,Td="must be a non-empty array of unique non-empty strings",VC="required non-empty array of non-empty strings";function qC(e){if(!Pt(e))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!Rd(e))return{errors:[vd],ruleNames:new Set};let t=[...e.rulebook_version===1||e.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],...qs(KC(e,e.rulebook_version===2),": ",": ")];return{errors:t.length>Ue.maxValidationErrors?[...t.slice(0,Ue.maxValidationErrors),wd]: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 KC(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")],...YC(e.allowed_commands),...ZC(e.rules,t),...eS(e.tests),...tS(e),...nS(e)]}function YC(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 ZC(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?QC(n,["rules",r]):XC(n,["rules",r])}),...xd(e)]}function XC(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 QC(e,t){return[...Od(e.name,t),...Dd(e.command,t),...Md(e.reason,t),...Nd(e.intent,t),...JC(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"],jC)]}function Nd(e,t){return e===void 0||Ys(e)?[]:[T([...t,"intent"],Vs)]}function JC(e,t){if(!Pt(e))return[T(t,"required object")];return[...Po(e.command_path,[...t,"command_path"],VC,!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 eS(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 tS(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 nS(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=Sd(e,t),r;try{r=cd(n.userConfigTarget,n.projectConfigTarget)}catch(m){if(m instanceof he)return mS(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:cS(o.config,i.config),command_tools:dS(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?uS(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=oS(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:rS(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 rS(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 oS(e,t,n){let r=iS(e),o=bd(t,r),i=aS(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}; ${sS(e)}`]};let s=lS(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 iS(e){return vo(e)?Ms(e).name:e}function sS(e){return vo(e)?`run ${yd} to vendor ${e}`:"create that file or remove that source from the rules config"}function aS(e,t){try{return{content:Eo(Sr(t,e))}}catch(n){if(n instanceof he)return{error:n.message};throw n}}function lS(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 cS(e,t){return[...new Set([...e?.transparent_wrappers??[],...t?.transparent_wrappers??[]])]}function dS(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 uS(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 mS(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 RS,readFileSync as _S}from"node: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,fS=new Map(Io.map((e)=>[e.id,e.intent]));function b(e,t){return{id:e,reason:t,intent:fS.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."},pS=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],gS=[{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"]},...gS.flatMap((e)=>pS.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"}],hS=[".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)=>hS.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?$/}],yS=[...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(yS.map((e)=>e.id));import{isAbsolute as oa,join as CS,normalize as SS,sep as Mo}from"node: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 vr(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=vr(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 bS="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",ES="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 vr(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 bS;return vS(r,t)?ES:null}function vS(e,t){let n=Lo(e),r=Lo(CS(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=SS(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=wS(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 wS(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=NS(Vt(e,t),e.home),r=Cd(e,t)?{exists:!1,policy:Yt(),errors:[]}:zo(An(t.cwd),e.home),o=AS(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?Rr(a.policy):n.policy,errors:l,...c?{fallback:c}:{},...r.exists?{policyScopes:{levelScope:d,weakenings:a?.weakenings??[],weakeningsIgnored:i}}:{}}}var xS="project policy audit settings are ignored; audit is user scope only";function AS(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?[]:[xS]}}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"},PS=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function TS(e,t){let n=[];return{policy:du(e,t,(o)=>{n.push(o)}),issues:n}}function IS(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,PS,[],n),{version:1,safety:{level:kS(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:OS(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 kS(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 OS(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(!RS(e))return{exists:!1,policy:Yt(),errors:[]};try{let n=_S(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=TS(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}: ${MS(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 DS=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 MS(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=DS.get(e.message)??e.message;return t===""?n:`${t}: ${n}`}function NS(e,t){let n=zo(e,t);if(!n.exists){let r=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!Me(r))return{policy:Rr(Yt()),errors:[]};let o=IS(r,t);return{policy:Rr(o),gui:o,errors:[],levelPresent:ru(r)}}if(n.parsed===void 0)return{policy:Rr(Yt()),errors:n.errors,...n.fallback?{fallback:n.fallback}:{}};return{policy:Rr(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 LS(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 Rr(e){return{safety:WS(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:LS(e.secret_protection.overrides),denyPaths:e.secret_protection.deny_paths,allowPaths:e.secret_protection.allow_paths}}}function WS(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}),...$S(l.spec)?{source:l.spec}:{}}:{},...c&&typeof c==="object"?{override:Object.freeze({type:"reason",reason:c.reason})}:{}})]})));return BS(o,FS(n,r),s,r.policyScopes)}function FS(e,t){let n=zS(t);if(e.errors.length===0&&e.warnings.length===0&&!n)return;return{diagnostics:[...e.errors,...e.warnings,...t.errors],reason:US(e.errors.length>0?GS(e.errors):void 0,e.warnings.length>0?ga(e.warnings.join("; ")):void 0,n)}}function GS(e){return`${ga(e.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function zS(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 $S(e){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(e)}function BS(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 US(...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:Rs({failClosed:n,paranoidRm:r,paranoidInterpreters:o}),strict:n,paranoidRm:r,paranoidInterpreters:o,worktreeMode:e.worktreeMode??!1}}import{dirname as _P,isAbsolute as xP,join as yg,parse as AP,resolve as PP,sep as TP}from"node:path";function _r(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&&jS(r))}var HS=/^@(['"])[ \t]*(?:\r\n|[\r\n])/;function In(e,t){let n=HS.exec(e.slice(t)),r=n?.[1];return n&&r?{quote:r,bodyStart:t+n[0].length}:null}function jS(e){return In(e.raw,0)!==null}var VS=/^[A-Za-z_][A-Za-z0-9_]*=/;function Bo(e,t){return e?.provenance==="literal"&&!e.quoted&&e.raw===t&&e.text===t}function xr(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)=>!VS.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===`
|
|
7
|
+
`||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);br(s,n)}return t}var Bs=new Set(["rm","find","rsync","xargs","parallel"]),xC=new Set(["git","busybox",...Bs,...Q,...Ed,...Fe]),AC=new Set(["python","node","ruby","perl"]);function _d(e){let t=N(e);return xC.has(t)||De(t)}function De(e){return AC.has(PC(e))}function PC(e){let t=k(e).toLowerCase();return Ro.test(t)?"python":t}function js(e){try{let t=Eo(TC(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=DC(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 TC(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(", ")}`,IC=/^[^/]+\/[^/]+$/,kC=["version","rules","overrides","transparent_wrappers","command_tools"],OC=/^[^\s\p{Cc}]{1,256}$/u,Us="non-empty, at most 256 characters, no whitespace or control characters";function DC(e){let t=MC(e);return{errors:qs(HC(t,kC,(n)=>n.kind==="custom"),": "," "),sources:UC(e,t)}}function MC(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")],...NC(e.rules,t),...FC(e.overrides),...zC(e.transparent_wrappers),...t?[]:WC(e.rules),...qt(e.overrides)?Object.keys(e.overrides).filter((n)=>!IC.test(n)).map((n)=>se(["overrides",n],"must use <rulebook-name>/<rule-name>")):[],...$C(e.transparent_wrappers),...BC(e.command_tools)]}function NC(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"),...LC(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 LC(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 WC(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 FC(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[...GC(n.reason,["overrides",t,"reason"]),...n.intent===void 0||Ys(n.intent)?[]:[T(["overrides",t,"intent"],Vs)]]})}function GC(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 zC(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 $C(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 BC(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"&&OC.test(e)}function UC(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 HC(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=qC(e);if(t.errors.length>0)throw Error(t.errors.join("; "));return e}var jC=`required non-empty string up to ${At} characters`,Td="must be a non-empty array of unique non-empty strings",VC="required non-empty array of non-empty strings";function qC(e){if(!Pt(e))return{errors:["Rulebook must be an object"],ruleNames:new Set};if(!Rd(e))return{errors:[vd],ruleNames:new Set};let t=[...e.rulebook_version===1||e.rulebook_version===2?[]:["rulebook_version must be 1 or 2"],...qs(KC(e,e.rulebook_version===2),": ",": ")];return{errors:t.length>Ue.maxValidationErrors?[...t.slice(0,Ue.maxValidationErrors),wd]: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 KC(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")],...YC(e.allowed_commands),...ZC(e.rules,t),...eS(e.tests),...tS(e),...nS(e)]}function YC(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 ZC(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?QC(n,["rules",r]):XC(n,["rules",r])}),...xd(e)]}function XC(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 QC(e,t){return[...Od(e.name,t),...Dd(e.command,t),...Md(e.reason,t),...Nd(e.intent,t),...JC(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"],jC)]}function Nd(e,t){return e===void 0||Ys(e)?[]:[T([...t,"intent"],Vs)]}function JC(e,t){if(!Pt(e))return[T(t,"required object")];return[...Po(e.command_path,[...t,"command_path"],VC,!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 eS(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 tS(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 nS(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=Sd(e,t),r;try{r=cd(n.userConfigTarget,n.projectConfigTarget)}catch(m){if(m instanceof he)return mS(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:cS(o.config,i.config),command_tools:dS(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?uS(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=oS(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:rS(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 rS(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 oS(e,t,n){let r=iS(e),o=bd(t,r),i=aS(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}; ${sS(e)}`]};let s=lS(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 iS(e){return vo(e)?Ms(e).name:e}function sS(e){return vo(e)?`run ${yd} to vendor ${e}`:"create that file or remove that source from the rules config"}function aS(e,t){try{return{content:Eo(Sr(t,e))}}catch(n){if(n instanceof he)return{error:n.message};throw n}}function lS(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 cS(e,t){return[...new Set([...e?.transparent_wrappers??[],...t?.transparent_wrappers??[]])]}function dS(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 uS(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 mS(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 RS,readFileSync as _S}from"node: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,fS=new Map(Io.map((e)=>[e.id,e.intent]));function b(e,t){return{id:e,reason:t,intent:fS.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."},pS=[".bak",".backup",".copy",".disabled",".old",".orig",".save",".tmp"],gS=[{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"]},...gS.flatMap((e)=>pS.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"}],hS=[".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)=>hS.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?$/}],yS=[...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(yS.map((e)=>e.id));import{isAbsolute as oa,join as CS,normalize as SS,sep as Mo}from"node: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 vr(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=vr(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 bS="cannot cover the home directory or a path above it (this would disable secret protection everywhere)",ES="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 vr(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 bS;return vS(r,t)?ES:null}function vS(e,t){let n=Lo(e),r=Lo(CS(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=SS(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=wS(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 wS(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=NS(Vt(e,t),e.home),r=Cd(e,t)?{exists:!1,policy:Yt(),errors:[]}:zo(An(t.cwd),e.home),o=AS(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?Rr(a.policy):n.policy,errors:l,...c?{fallback:c}:{},...r.exists?{policyScopes:{levelScope:d,weakenings:a?.weakenings??[],weakeningsIgnored:i}}:{}}}var xS="project policy audit settings are ignored; audit is user scope only";function AS(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?[]:[xS]}}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"},PS=["version","safety","workflow","destructive_command_protection","secret_protection","audit"];function TS(e,t){let n=[];return{policy:du(e,t,(o)=>{n.push(o)}),issues:n}}function IS(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,PS,[],n),{version:1,safety:{level:kS(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:OS(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 kS(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 OS(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(!RS(e))return{exists:!1,policy:Yt(),errors:[]};try{let n=_S(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=TS(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}: ${MS(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 DS=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 MS(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=DS.get(e.message)??e.message;return t===""?n:`${t}: ${n}`}function NS(e,t){let n=zo(e,t);if(!n.exists){let r=globalThis.__CC_SAFETY_NET_EMBEDDED_POLICY__;if(!Me(r))return{policy:Rr(Yt()),errors:[]};let o=IS(r,t);return{policy:Rr(o),gui:o,errors:[],levelPresent:ru(r)}}if(n.parsed===void 0)return{policy:Rr(Yt()),errors:n.errors,...n.fallback?{fallback:n.fallback}:{}};return{policy:Rr(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 LS(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 Rr(e){return{safety:WS(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:LS(e.secret_protection.overrides),denyPaths:e.secret_protection.deny_paths,allowPaths:e.secret_protection.allow_paths}}}function WS(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}),...$S(l.spec)?{source:l.spec}:{}}:{},...c&&typeof c==="object"?{override:Object.freeze({type:"reason",reason:c.reason})}:{}})]})));return BS(o,FS(n,r),s,r.policyScopes)}function FS(e,t){let n=zS(t);if(e.errors.length===0&&e.warnings.length===0&&!n)return;return{diagnostics:[...e.errors,...e.warnings,...t.errors],reason:US(e.errors.length>0?GS(e.errors):void 0,e.warnings.length>0?ga(e.warnings.join("; ")):void 0,n)}}function GS(e){return`${ga(e.join("; "))} Those rule sources are not active; every other rule and all built-in protections still apply`}function zS(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 $S(e){return/^(?:[A-Za-z0-9_.-]+$|https:\/\/github\.com\/|github:|gh:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#|$))/.test(e)}function BS(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 US(...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:Rs({failClosed:n,paranoidRm:r,paranoidInterpreters:o}),strict:n,paranoidRm:r,paranoidInterpreters:o,worktreeMode:e.worktreeMode??!1}}import{dirname as _P,isAbsolute as xP,join as yg,parse as AP,resolve as PP,sep as TP}from"node:path";function _r(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&&jS(r))}var HS=/^@(['"])[ \t]*(?:\r\n|[\r\n])/;function In(e,t){let n=HS.exec(e.slice(t)),r=n?.[1];return n&&r?{quote:r,bodyStart:t+n[0].length}:null}function jS(e){return In(e.raw,0)!==null}var VS=/^[A-Za-z_][A-Za-z0-9_]*=/;function Bo(e,t){return e?.provenance==="literal"&&!e.quoted&&e.raw===t&&e.text===t}function xr(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)=>!VS.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
8
|
`||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 Ca(e,t,n,r){let o=[],i=t;for(let s of r){let a=i,l=!1;while(i<n){let c=qS(e,i,n);if((s.stripTabs?c.text.replace(/^\t+/,""):c.text)===s.delimiter){s.attach({body:s.stripTabs?KS(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]!==`
|
|
9
9
|
`&&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 qS(e,t,n){let r=t;while(r<n&&e[r]!==`
|
|
10
10
|
`)r++;let o=r>=n?n:r+1;return{text:e.slice(t,r),contentEnd:r,next:o}}function KS(e){return e.replace(/(^|\r\n?|\n)\t+/g,"$1")}var Su=new Set(["&&","||","|","|&"]),YS=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,...ib(e,r.quotedExpansionEnd,o.nodes)?[Ru]:[],...rb.test(e)?[wu]:[]];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(),Cu(a,l),{nodes:a,issues:l,next:f+1,closed:!0,limited:!1,pendingHeredocs:d};if(Pr(m)){if(m.charCodeAt(0)>127)l.push(wu);if(m===`
|
|
@@ -52,6 +52,6 @@ var hc={id:"cc-safety-net",name:"CC Safety Net",description:"Block destructive c
|
|
|
52
52
|
`).some((n)=>{let r=n.indexOf(t);return r>=0&&/[()[\]{}]/.test(n.slice(r))})}function FI(e,t){return VI.test(e)||t.some((n)=>{let r=jI.get(n.name),o=n.index+n.name.length;return r!==void 0&&!r.test(e.slice(o,o+40))})}function GI(e){return e.some((t)=>dh(t.name).some((n)=>LI.test(n)))}var zI=new Set(["cmd","powershell","pwsh"]);function $I(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(ve(s.text).toLowerCase())||zI.has(ve(s.text).toLowerCase().replace(/\.exe$/,""))))}function BI(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 ek(e,a);let u=(c===s||c===",")&&(d===","||d===oc[s]||s==="{"&&d===":");if(s!=="(")return u&&s!=="";return u&&(o&&HI.test(e.slice(Math.max(0,i-20),i))||(c===","||d===",")&&tk(e,i))}function UI(e,t,n,r){let o=Math.max(0,t.tokenStart-80),i=`${o===0?`
|
|
53
53
|
`:""}${e.slice(o,t.tokenStart)}`,s=qI.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 HI=/(?:^|[^\w$.])(?:print|console\s*\.\s*log)\s*$/,jI=new Map([["print",/^\s*\(/],["console",/^\s*\.\s*[\w$]+\s*\(/]]),VI=/(?:^|[^\w$])(?:as|class|const|def|function|import|let|var)\s+(?:print|console)(?![\w$])/,qI=/[;\n{]\s*(?:(?:const|let|var)\s+)?([A-Za-z_$][\w$]*)\s*=\s*$/,KI=/(?:^|[^\w$.])(?:pathlib\s*\.\s*)?Path\s*$/,YI=/^\s*\.\s*write_(?:text|bytes)\s*\(/,ZI=/(?:^|[^\w$.])open\s*$/,XI=/^[bt]*[awx][abtwx]*$/,QI=/(?:^|[^\w$])(?:writeFile|writeFileSync|appendFile|appendFileSync|Bun\s*\.\s*write)\s*$/;function JI(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(KI.test(a))return(o===r||e.masked[o]===",")&&(s===","||s===")")&&!e.literals.some((c)=>c.tokenStart>r&&c.tokenStart<t.tokenStart)&&YI.test(e.masked.slice(vi(e.masked,r+1)+1));if(o!==r||s!==",")return!1;if(QI.test(a))return!0;if(!ZI.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&&XI.test(l.text)&&/^[,)]/.test(e.masked.slice(yn(e.masked,l.tokenEnd)))}function ek(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 tk(e,t){let n=sr(e,t),r=e.slice(Math.max(0,n-7),n+1);return!/[\w$)\]]$/.test(r)||MI.test(r)}function nk(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 rk={python:"#",javascript:"/"};function ok(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===rk[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(aI.test(e.slice(s)))return null}let l=a==="'"||a==='"'||n==="javascript"&&a==="`"?a:null;if(l===null)continue;if(l==="`"&&lk(e,s))return null;let c=n==="python"?sk(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?ik(e,m,u,d,n,r):ak(e,u,d);if(p===null)return null;if(!f){let g=e.slice(u,p);if(n==="simple"&&l==='"'&&lI.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 ik(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===`
|
|
54
54
|
`||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 sk(e,t){return sI.exec(e.slice(Math.max(0,t-3),t))?.[1]??""}function ak(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===`
|
|
55
|
-
`||i==="\r"))return null;if(e.startsWith(n,o))return o}return null}function lk(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 ck(e){for(let t of e.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let n=t[0],r=t.index;if(UT.has(n.toLowerCase()))return!0;let o=dh(n);if(!o.some((i)=>HT.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 dk(e,t,n,r,o,i){return gk(e).flatMap((s)=>{let a=t.getShellSyntax(s);if(a.status==="invalid")return[];return[...lr(a,t,{...n,displayOperandsAreCapturedOutput:!0},r,o,i),...uk(a,r)?mk(a,r).map((l)=>({target:l,cwd:o})):[]]})}function uk(e,t){let n=mi(e);for(let r=0;r<n.length;r++){let o=n[r];if(o?.kind!=="word"||ve(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 mk(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=pk(e);if(t===null)return[];let n=Buffer.from(t,"base64").toString("utf8");if(n===""||fk(n))return[];return Buffer.from(n,"utf8").toString("base64").replace(/=+$/g,"")===t.replace(/=+$/g,"")?[n]:[]}function fk(e){return Array.from(e).some((t)=>{let n=t.charCodeAt(0);return n<32||n===127})}function pk(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 gk(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(br(o,n))continue;if(uh(e,r,n)){let i=hk(e,r+1);if(i!==null)t.push(i.body),r=i.endIndex;continue}if(!n.inSingle&&o==="`"){let i=yk(e,r);if(i!==null)t.push(i.body),r=i.endIndex}}return t}function hk(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(br(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 yk(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 Ck(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===tI)o=!0;if(rI.has(u))r=!0;if(f!==void 0){if(u===Fg)t.push(f);continue}if(iI.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(nI.has(h))r=!0;if(oI.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 Sk(e){return e==="env"||e==="command"||e==="builtin"||e==="sudo"}var bk=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),Vg=".env.",Ek=[".example",".sample",".template",".tpl"],vk=[".env.example.",".env.sample."];function wk(e){let t;try{t=new URL(e.trim())}catch{return!1}return t.protocol!=="file:"&&t.host!==""}function Rk(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 so(e,t,n,r)}catch(o){if(o instanceof z)throw o;return""}}var _k=/[?&][^?&=/]+=/,xk=new Set(["node_modules","__pycache__"]),Ak=[["vendor","bundle"],["vendor","cache"]];function Pk(e,t,n,r,o){if(wk(e))return null;let i=Ie(e,t,r,o);if(!i)return null;let s=H(i.split("/").pop()??""),a=H(i),l=()=>Rk(s)||rs(e,t,r,o),c=H(Mk(e,t,r,o));for(let f of Qs){let m=`~/${f.suffixParts.join("/")}`;if((Kg(a,m)||Kg(c,m))&&vt(f.id,n))return f.id}if(s===".env.defaults"||s.startsWith(Vg)&&Ek.some((f)=>s.endsWith(f))||vk.some((f)=>s.startsWith(f)))return null;let d=Tk(i,t,n,r,o);if(d)return d;if(bk.has(s))return null;for(let f of Xs)if(s===f.basename&&vt(f.id,n))return f.id;if(s.startsWith(Vg)&&vt(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==="_")&&vt(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&&vt(f.id,n))return f.id}if(Ok(a))return null;if(!s.includes(".")&&Er.pattern.test(s)&&vt(Er.id,n))return Er.id;if(_k.test(e)&&!rs(e,t,r,o))return null;let u=Dk(s,n);if(u)return u;return null}function Tk(e,t,n,r,o){return Oo.find((i)=>{if(!vt(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"])||oo(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()?oo(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)=>oo(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()?oo(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()?oo(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"&&Cn(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)=>Cn(H(e),H(oe(t,r))))}function oo(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 Ik(e,t,n,r,o,i){if(n.length===0)return!1;let s=H(so(e,t,o,i));return n.some((a)=>Cn(s,H(so(a,r,o,i))))}function kk(e,t,n,r,o,i){if(n.length===0)return!1;let s=H(so(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&&Cn(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(so(m?.root??f,r,o,i));if(!p)return!1;if(c&&(c===p||c.startsWith(p.endsWith("/")?p:`${p}/`)))return!1;return Cn(s,p)&&!(m&&s===p)})}function Ok(e){let t=e.split("/");return t.some((n)=>xk.has(n))||Ak.some(([n,r])=>t.some((o,i)=>o===n&&t[i+1]===r))}function Dk(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&&vt(o.id,t))return o.id;for(let o of na)if(o.pattern.test(r)&&vt(o.id,t))return o.id;return null}function H(e){return e.toLowerCase()}function vt(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(!Cn(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 Mk(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!==""&&Cn(c(a),c(f)));if(d===void 0)return"";let u=a.slice(d.length);return u?`~${u}`:"~"}function so(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(Nk(ht(e,t))));return{home:o,normalized:i}}function Nk(e){if(!e.trim().toLowerCase().startsWith("file:"))return e;try{return LT(e)}catch{return e}}function ac(e,t){if(e==="~")return t;if(e.startsWith("~/"))return oe(t,e.slice(2));return e}function Lk(e){if(process.platform==="win32")return!0;return NT.parse(e).root.length>1}function Qe(e){let t=e.trim(),n=(t.includes("\\")&&Lk(t)?t.replace(/\\/g,"/"):t).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(n==="/")return n;return n.replace(/\/+$/g,"")}function Cn(e,t){return e===t||e.startsWith(t.endsWith("/")?t:`${t}/`)}function ve(e){return e.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??e}class Sn 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 Wk={findPolicyMutation:Mg,findGitMetadataMutation:Fm,resolveGitMetadata:$k,loadPolicySnapshot:mu,findSensitiveTarget:eh,analyzeCommand:_g,getModes:_s},Fk=/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/,Gk=["workdir","cwd","working_directory"];function lc(e,t){let n={...Wk,...t.dependencies},r=Hk(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?zk(e,r,s.cwd,t.environment.paths):e;if("decision"in a)return a;let l=a,c=l===e?{}:{promotedInvocation:l},d=ao(l)?l.command:r,u=Gt("policy-protection",d,()=>Mm(l)),f=$n(u,"input-candidate"),m=$n(u,"declared-command");if(ao(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=we(),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 C=Gt("policy-protection",d,()=>Tg(u,t.environment,p));if(C){let L=d??C.target;return{stage:"policy-protection",...c,decision:{kind:"deny",reason:Pg,ruleId:"guard.policy-apply",intent:"hard_stop",evidence:{command:L,segment:C.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 S=i??o(),E=S.policy,A=n.getModes(E,t.environment.env),P={level:A.effectiveLevel,...Bk(S),...c},I=E.secretProtection.enabled===!1?null:Gt("secret-protection",d,()=>n.findSensitiveTarget(u,E.secretProtection,t.environment,p,{strict:ao(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(!ao(l))return{stage:"non-command",...P,decision:{kind:"allow"}};if(!l.command||l.command.trim()==="")return{...gh(d),...P};let v=Gt("command-analysis",d,()=>xg(()=>n.analyzeCommand(l.command,{cwd:l.context.configCwd,effectiveCwd:l.context.executionCwd,shell:l.route.shell,policySnapshot:S,environment:t.environment,protectedGitMetadata:g,effectiveCapabilities:A.capabilities,worktreeMode:A.worktreeMode,budget:p,...t.trace?{trace:t.trace}:{}},Uk(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:()=>S,resolveGitMetadata:()=>g}}),...c};return{decision:re.decision,withItsTrace:()=>(L?.adopt(),re)}}:void 0;if(v.decision){let L=!A.strict&&(v.decision.ruleId==="raw-text.dangerous-command"||v.decision.reason===rn&&!Fk.test(v.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 v?{errorCode:v.errorCode}:{},decision:L?{...v.decision,unverifiedByStandardMode:!0}:v.decision}}return G?.().withItsTrace()??{stage:"command-analysis",...P,decision:{kind:"allow"}}}function zk(e,t,n,r){let o=[...new Set((n?[n]:Gk).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:Ss(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 po(e.toolName,e.input,{kind:"command",shell:"auto"},{configCwd:e.context.configCwd,executionCwd:a},t)}function $k(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 Bk(e){if(e.state==="ready")return{};return{configFallback:{reason:e.reason}}}function Uk(e){return $n(e,"declared-command")?.program}function Hk(e){try{return gr(e.input)}catch(t){let n=ao(e)?e.command:void 0;throw new Sn("policy-protection",ph("policy-protection",t instanceof ct?void 0:n,t),t)}}function Gt(e,t,n){try{return n()}catch(r){throw new Sn(e,ph(e,r instanceof ct?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:ls,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 ao(e){return e.route.kind==="command"}import{appendFileSync as rO,mkdirSync as oO}from"node:fs";import{isAbsolute as iO,join as uc}from"node:path";import{lstatSync as yh,readdirSync as jk,readFileSync as Vk,rmdirSync as qk,statSync as Ch,unlinkSync as Kk,utimesSync as Yk,writeFileSync as Zk}from"node:fs";import{join as lo}from"node:path";function hh(e,t={}){return zo(Vt(e,t),e.home).policy.audit.retention_days}var dc=86400000,Xk=".last-prune",Qk=/^\d{4}-\d{2}$/,Jk=/^((\d{4}-\d{2})-\d{2})-.+\.jsonl$/,Sh=(e)=>Math.floor(e/dc);function Eh(e,t,n=()=>new Date){try{let r=n().getTime();if(!Ch(t,{throwIfNoEntry:!1})?.isDirectory())return;let o=lo(t,Xk),i=Ch(o,{throwIfNoEntry:!1})?.mtimeMs;if(i!==void 0&&Sh(i)===Sh(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()){eO(lo(t,l.name),s,a);continue}if(l.isFile()&&l.name.endsWith(".jsonl"))tO(lo(t,l.name),s)}Zk(o,"",{mode:384}),Yk(o,r/1000,r/1000)}catch{}}function eO(e,t,n){for(let r of cc(e)){if(!r.isDirectory()||!Qk.test(r.name))continue;let o=lo(e,r.name);for(let i of cc(o)){if(!i.isFile())continue;let s=Jk.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;vh(lo(o,i.name))}if(r.name!==n)bh(o)}bh(e)}function tO(e,t){try{let n=yh(e);if(n.mtimeMs>=t)return;let r=Vk(e,"utf-8").split(`
|
|
56
|
-
`).filter((o)=>o.trim()).map(nO);if(r.length===0)return;if(r.some((o)=>o===void 0||o>=t))return;if(yh(e).mtimeMs!==n.mtimeMs)return;vh(e)}catch{}}function nO(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 jk(e,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function vh(e){try{Kk(e)}catch{}}function bh(e){try{qk(e)}catch{}}var sO="2.7.
|
|
55
|
+
`||i==="\r"))return null;if(e.startsWith(n,o))return o}return null}function lk(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 ck(e){for(let t of e.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)){let n=t[0],r=t.index;if(UT.has(n.toLowerCase()))return!0;let o=dh(n);if(!o.some((i)=>HT.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 dk(e,t,n,r,o,i){return gk(e).flatMap((s)=>{let a=t.getShellSyntax(s);if(a.status==="invalid")return[];return[...lr(a,t,{...n,displayOperandsAreCapturedOutput:!0},r,o,i),...uk(a,r)?mk(a,r).map((l)=>({target:l,cwd:o})):[]]})}function uk(e,t){let n=mi(e);for(let r=0;r<n.length;r++){let o=n[r];if(o?.kind!=="word"||ve(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 mk(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=pk(e);if(t===null)return[];let n=Buffer.from(t,"base64").toString("utf8");if(n===""||fk(n))return[];return Buffer.from(n,"utf8").toString("base64").replace(/=+$/g,"")===t.replace(/=+$/g,"")?[n]:[]}function fk(e){return Array.from(e).some((t)=>{let n=t.charCodeAt(0);return n<32||n===127})}function pk(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 gk(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(br(o,n))continue;if(uh(e,r,n)){let i=hk(e,r+1);if(i!==null)t.push(i.body),r=i.endIndex;continue}if(!n.inSingle&&o==="`"){let i=yk(e,r);if(i!==null)t.push(i.body),r=i.endIndex}}return t}function hk(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(br(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 yk(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 Ck(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===tI)o=!0;if(rI.has(u))r=!0;if(f!==void 0){if(u===Fg)t.push(f);continue}if(iI.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(nI.has(h))r=!0;if(oI.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 Sk(e){return e==="env"||e==="command"||e==="builtin"||e==="sudo"}var bk=new Set(["id_rsa.pub","id_ed25519.pub","id_ecdsa.pub"]),Vg=".env.",Ek=[".example",".sample",".template",".tpl"],vk=[".env.example.",".env.sample."];function wk(e){let t;try{t=new URL(e.trim())}catch{return!1}return t.protocol!=="file:"&&t.host!==""}function Rk(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 so(e,t,n,r)}catch(o){if(o instanceof z)throw o;return""}}var _k=/[?&][^?&=/]+=/,xk=new Set(["node_modules","__pycache__"]),Ak=[["vendor","bundle"],["vendor","cache"]];function Pk(e,t,n,r,o){if(wk(e))return null;let i=Ie(e,t,r,o);if(!i)return null;let s=H(i.split("/").pop()??""),a=H(i),l=()=>Rk(s)||rs(e,t,r,o),c=H(Mk(e,t,r,o));for(let f of Qs){let m=`~/${f.suffixParts.join("/")}`;if((Kg(a,m)||Kg(c,m))&&vt(f.id,n))return f.id}if(s===".env.defaults"||s.startsWith(Vg)&&Ek.some((f)=>s.endsWith(f))||vk.some((f)=>s.startsWith(f)))return null;let d=Tk(i,t,n,r,o);if(d)return d;if(bk.has(s))return null;for(let f of Xs)if(s===f.basename&&vt(f.id,n))return f.id;if(s.startsWith(Vg)&&vt(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==="_")&&vt(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&&vt(f.id,n))return f.id}if(Ok(a))return null;if(!s.includes(".")&&Er.pattern.test(s)&&vt(Er.id,n))return Er.id;if(_k.test(e)&&!rs(e,t,r,o))return null;let u=Dk(s,n);if(u)return u;return null}function Tk(e,t,n,r,o){return Oo.find((i)=>{if(!vt(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"])||oo(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()?oo(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)=>oo(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()?oo(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()?oo(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"&&Cn(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)=>Cn(H(e),H(oe(t,r))))}function oo(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 Ik(e,t,n,r,o,i){if(n.length===0)return!1;let s=H(so(e,t,o,i));return n.some((a)=>Cn(s,H(so(a,r,o,i))))}function kk(e,t,n,r,o,i){if(n.length===0)return!1;let s=H(so(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&&Cn(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(so(m?.root??f,r,o,i));if(!p)return!1;if(c&&(c===p||c.startsWith(p.endsWith("/")?p:`${p}/`)))return!1;return Cn(s,p)&&!(m&&s===p)})}function Ok(e){let t=e.split("/");return t.some((n)=>xk.has(n))||Ak.some(([n,r])=>t.some((o,i)=>o===n&&t[i+1]===r))}function Dk(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&&vt(o.id,t))return o.id;for(let o of na)if(o.pattern.test(r)&&vt(o.id,t))return o.id;return null}function H(e){return e.toLowerCase()}function vt(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(!Cn(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 Mk(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!==""&&Cn(c(a),c(f)));if(d===void 0)return"";let u=a.slice(d.length);return u?`~${u}`:"~"}function so(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(Nk(ht(e,t))));return{home:o,normalized:i}}function Nk(e){if(!e.trim().toLowerCase().startsWith("file:"))return e;try{return LT(e)}catch{return e}}function ac(e,t){if(e==="~")return t;if(e.startsWith("~/"))return oe(t,e.slice(2));return e}function Lk(e){if(process.platform==="win32")return!0;return NT.parse(e).root.length>1}function Qe(e){let t=e.trim(),n=(t.includes("\\")&&Lk(t)?t.replace(/\\/g,"/"):t).replace(/\/{2,}/g,"/").replace(/^\.\//,"");if(n==="/")return n;return n.replace(/\/+$/g,"")}function Cn(e,t){return e===t||e.startsWith(t.endsWith("/")?t:`${t}/`)}function ve(e){return e.split(/[\\/]/).pop()?.replace(/\.exe$/i,"")??e}class Sn 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 Wk={findPolicyMutation:Mg,findGitMetadataMutation:Fm,resolveGitMetadata:$k,loadPolicySnapshot:mu,findSensitiveTarget:eh,analyzeCommand:_g,getModes:_s},Fk=/^(?:\S*\/)?(?:ba|da|z|k)?sh(?:\s+-[A-Za-z-]*)*$/,Gk=["workdir","cwd","working_directory"];function lc(e,t){let n={...Wk,...t.dependencies},r=Hk(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?zk(e,r,s.cwd,t.environment.paths):e;if("decision"in a)return a;let l=a,c=l===e?{}:{promotedInvocation:l},d=ao(l)?l.command:r,u=Gt("policy-protection",d,()=>Mm(l)),f=$n(u,"input-candidate"),m=$n(u,"declared-command");if(ao(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=we(),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 C=Gt("policy-protection",d,()=>Tg(u,t.environment,p));if(C){let L=d??C.target;return{stage:"policy-protection",...c,decision:{kind:"deny",reason:Pg,ruleId:"guard.policy-apply",intent:"hard_stop",evidence:{command:L,segment:C.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 S=i??o(),E=S.policy,A=n.getModes(E,t.environment.env),P={level:A.effectiveLevel,...Bk(S),...c},I=E.secretProtection.enabled===!1?null:Gt("secret-protection",d,()=>n.findSensitiveTarget(u,E.secretProtection,t.environment,p,{strict:ao(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(!ao(l))return{stage:"non-command",...P,decision:{kind:"allow"}};if(!l.command||l.command.trim()==="")return{...gh(d),...P};let v=Gt("command-analysis",d,()=>xg(()=>n.analyzeCommand(l.command,{cwd:l.context.configCwd,effectiveCwd:l.context.executionCwd,shell:l.route.shell,policySnapshot:S,environment:t.environment,protectedGitMetadata:g,effectiveCapabilities:A.capabilities,worktreeMode:A.worktreeMode,budget:p,...t.trace?{trace:t.trace}:{}},Uk(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:()=>S,resolveGitMetadata:()=>g}}),...c};return{decision:re.decision,withItsTrace:()=>(L?.adopt(),re)}}:void 0;if(v.decision){let L=!A.strict&&(v.decision.ruleId==="raw-text.dangerous-command"||v.decision.reason===rn&&!Fk.test(v.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 v?{errorCode:v.errorCode}:{},decision:L?{...v.decision,unverifiedByStandardMode:!0}:v.decision}}return G?.().withItsTrace()??{stage:"command-analysis",...P,decision:{kind:"allow"}}}function zk(e,t,n,r){let i=[...new Set((n===!1?[]:n?[n]:Gk).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:Ss(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 po(e.toolName,e.input,{kind:"command",shell:"auto"},{configCwd:e.context.configCwd,executionCwd:l},t)}function $k(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 Bk(e){if(e.state==="ready")return{};return{configFallback:{reason:e.reason}}}function Uk(e){return $n(e,"declared-command")?.program}function Hk(e){try{return gr(e.input)}catch(t){let n=ao(e)?e.command:void 0;throw new Sn("policy-protection",ph("policy-protection",t instanceof ct?void 0:n,t),t)}}function Gt(e,t,n){try{return n()}catch(r){throw new Sn(e,ph(e,r instanceof ct?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:ls,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 ao(e){return e.route.kind==="command"}import{appendFileSync as rO,mkdirSync as oO}from"node:fs";import{isAbsolute as iO,join as uc}from"node:path";import{lstatSync as yh,readdirSync as jk,readFileSync as Vk,rmdirSync as qk,statSync as Ch,unlinkSync as Kk,utimesSync as Yk,writeFileSync as Zk}from"node:fs";import{join as lo}from"node:path";function hh(e,t={}){return zo(Vt(e,t),e.home).policy.audit.retention_days}var dc=86400000,Xk=".last-prune",Qk=/^\d{4}-\d{2}$/,Jk=/^((\d{4}-\d{2})-\d{2})-.+\.jsonl$/,Sh=(e)=>Math.floor(e/dc);function Eh(e,t,n=()=>new Date){try{let r=n().getTime();if(!Ch(t,{throwIfNoEntry:!1})?.isDirectory())return;let o=lo(t,Xk),i=Ch(o,{throwIfNoEntry:!1})?.mtimeMs;if(i!==void 0&&Sh(i)===Sh(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()){eO(lo(t,l.name),s,a);continue}if(l.isFile()&&l.name.endsWith(".jsonl"))tO(lo(t,l.name),s)}Zk(o,"",{mode:384}),Yk(o,r/1000,r/1000)}catch{}}function eO(e,t,n){for(let r of cc(e)){if(!r.isDirectory()||!Qk.test(r.name))continue;let o=lo(e,r.name);for(let i of cc(o)){if(!i.isFile())continue;let s=Jk.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;vh(lo(o,i.name))}if(r.name!==n)bh(o)}bh(e)}function tO(e,t){try{let n=yh(e);if(n.mtimeMs>=t)return;let r=Vk(e,"utf-8").split(`
|
|
56
|
+
`).filter((o)=>o.trim()).map(nO);if(r.length===0)return;if(r.some((o)=>o===void 0||o>=t))return;if(yh(e).mtimeMs!==n.mtimeMs)return;vh(e)}catch{}}function nO(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 jk(e,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function vh(e){try{Kk(e)}catch{}}function bh(e){try{qk(e)}catch{}}var sO="2.7.5",aO=1e4,lO=2000,cO=256,dO=32768;function uO(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 mO(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=uO(t);if(!a)return;let l=pO(e);if(!l)return;try{let c=(s.now??(()=>new Date))().toISOString(),d=is(Rt(n),s.failureStage?Number.POSITIVE_INFINITY:aO),u=is(Rt(r),lO),f=s.toolName?is(Rt(s.toolName),cO):void 0,m=i===null?void 0:is(Rt(i),dO),p=uc(l,mO(m?.value??null),c.slice(0,7));oO(p,{recursive:!0,mode:448});let g=uc(p,`${c.slice(0,10)}-${a}.jsonl`),h={ts:c,id:(s.createId??xs)(),v:sO,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};rO(g,`${JSON.stringify(h)}
|
|
57
57
|
`,{encoding:"utf-8",mode:384}),Eh(e,l,s.now)}catch{}}function is(e,t){return{value:e.slice(0,t),truncated:e.length>t}}function fO(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&&iO(n)?n:null}function pO(e){let t=fO(e);return t?uc(t,".cc-safety-net","logs"):null}function Rh(e,t,n,r=!0,o){if(t.decision.kind==="allow"){if(!n||e.route.kind!=="command")return;let a=wh(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?wh(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 wh(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 Sn))throw r;throw Ah(e,t,r.evaluation,n,!(r.cause instanceof ct),{stage:r.stage,errorCode:gO(r.cause)}),r}}function Ah(e,t,n,r,o=!0,i){_h(e,Rh(n.promotedInvocation??t,n,r.guard?.auditAllowed??!1,o,i),r.audit.getSessionId,{agent:r.audit.agent,shape:r.audit.shape})}function gO(e){if(e instanceof z)return K[e.kind].errorCode;if(e instanceof ct)return"tool-input-limit";if(e instanceof qe)return"structural-shell-syntax-limit";if(e instanceof on)return"unparseable-command";return"unexpected-error"}function co(e,t={}){return{malformed:!0,denial:ur(t),cwd:e}}function ss(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 hO(n,r,e,t)}catch(o){return console.error("CC Safety Net error:",o),e.block(dr())}}}function hO(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=yc(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 Sn))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 Ih="exec",yO=new Set(["auto","gateway"]);function kh(e){e.on("before_tool_call",CO(e),{matcher:[Ih],priority:50})}function CO(e,t={}){return Th({agent:"openclaw",debugLabel:"openclaw before_tool_call",extract:(r,o,i)=>SO(r,o,e,i),getSessionId:(r,o)=>o.sessionId??o.sessionKey,allow:void 0,block:(r)=>EO(r),includeEvidenceOnError:()=>!0,cancelled:(r)=>r.abortSignal?.aborted===!0},t)}function SO(e,t,n,r){if(!e||typeof e!=="object")return ss(null);let o=e.toolName;if(typeof o!=="string"||o.trim()==="")return co(null);if(o!==Ih)return;if(e.toolKind!==void 0)return;let i=e.params;if(!i||typeof i!=="object"||Array.isArray(i))return co(null,{toolName:o});let s=i,a=s.command;if(typeof a!=="string"||a.trim()==="")return co(null,{toolName:o});if(s.host!==void 0&&!yO.has(s.host))return ss(null,{command:a,toolName:o});let l=bO(n,t.agentId);if(!l)return ss(null,{command:a,toolName:o});let c=Cs(".",[l],r);if(!c)return fc({directory:"session",problem:"unusable",cwd:l},{command:a,toolName:o});let d=s.workdir;if(d!==void 0&&(typeof d!=="string"||d.trim()===""))return co(c,{command:a,toolName:o});let u=typeof d==="string"?d:".",f=Cs(u,[c],r);if(!f)return fc({directory:"requested",problem:$c(u,c,r),cwd:u},{command:a,toolName:o});return po(o,s,{kind:"command",shell:"auto"},{configCwd:c,executionCwd:f},a)}function bO(e,t){if(typeof t!=="string"||t.trim()==="")return;try{let n=e.runtime.agent.resolveAgentWorkspaceDir(e.config,t);return typeof n==="string"&&n.trim()!==""?n:void 0}catch{return}}function EO(e){return{block:!0,blockReason:Cc(e)}}var Oz={...hc,register:kh};export{Oz as default};
|