failproofai 1.0.2-beta.2 → 1.0.2-beta.4

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.
Files changed (183) hide show
  1. package/.next/standalone/.next/BUILD_ID +1 -1
  2. package/.next/standalone/.next/build-manifest.json +6 -6
  3. package/.next/standalone/.next/prerender-manifest.json +3 -3
  4. package/.next/standalone/.next/required-server-files.json +1 -1
  5. package/.next/standalone/.next/server/app/_global-error/page/build-manifest.json +3 -3
  6. package/.next/standalone/.next/server/app/_global-error/page/server-reference-manifest.json +1 -1
  7. package/.next/standalone/.next/server/app/_global-error/page.js.nft.json +1 -1
  8. package/.next/standalone/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  9. package/.next/standalone/.next/server/app/_global-error.html +1 -1
  10. package/.next/standalone/.next/server/app/_global-error.rsc +7 -7
  11. package/.next/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +6 -6
  12. package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +7 -7
  13. package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  14. package/.next/standalone/.next/server/app/_not-found/page/build-manifest.json +3 -3
  15. package/.next/standalone/.next/server/app/_not-found/page/server-reference-manifest.json +1 -1
  16. package/.next/standalone/.next/server/app/_not-found/page.js.nft.json +1 -1
  17. package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  18. package/.next/standalone/.next/server/app/_not-found.html +1 -1
  19. package/.next/standalone/.next/server/app/_not-found.rsc +14 -14
  20. package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +14 -14
  21. package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +13 -13
  22. package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  23. package/.next/standalone/.next/server/app/api/audit/invite/route.js +2 -3
  24. package/.next/standalone/.next/server/app/api/audit/invite/route.js.nft.json +1 -1
  25. package/.next/standalone/.next/server/app/api/audit/run/route.js +4 -5
  26. package/.next/standalone/.next/server/app/api/audit/run/route.js.nft.json +1 -1
  27. package/.next/standalone/.next/server/app/api/audit/status/route.js.nft.json +1 -1
  28. package/.next/standalone/.next/server/app/api/auth/login-request/route.js +2 -2
  29. package/.next/standalone/.next/server/app/api/auth/login-request/route.js.nft.json +1 -1
  30. package/.next/standalone/.next/server/app/api/auth/login-verify/route.js +3 -4
  31. package/.next/standalone/.next/server/app/api/auth/login-verify/route.js.nft.json +1 -1
  32. package/.next/standalone/.next/server/app/api/auth/logout/route.js +4 -4
  33. package/.next/standalone/.next/server/app/api/auth/logout/route.js.nft.json +1 -1
  34. package/.next/standalone/.next/server/app/api/auth/status/route.js +4 -4
  35. package/.next/standalone/.next/server/app/api/auth/status/route.js.nft.json +1 -1
  36. package/.next/standalone/.next/server/app/api/download/[project]/[session]/route.js.nft.json +1 -1
  37. package/.next/standalone/.next/server/app/audit/page/build-manifest.json +3 -3
  38. package/.next/standalone/.next/server/app/audit/page/server-reference-manifest.json +2 -2
  39. package/.next/standalone/.next/server/app/audit/page.js.nft.json +1 -1
  40. package/.next/standalone/.next/server/app/audit/page_client-reference-manifest.js +1 -1
  41. package/.next/standalone/.next/server/app/index.html +1 -1
  42. package/.next/standalone/.next/server/app/index.rsc +14 -14
  43. package/.next/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +13 -13
  44. package/.next/standalone/.next/server/app/index.segments/_full.segment.rsc +14 -14
  45. package/.next/standalone/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  46. package/.next/standalone/.next/server/app/page/build-manifest.json +3 -3
  47. package/.next/standalone/.next/server/app/page/server-reference-manifest.json +1 -1
  48. package/.next/standalone/.next/server/app/page.js.nft.json +1 -1
  49. package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
  50. package/.next/standalone/.next/server/app/policies/page/build-manifest.json +3 -3
  51. package/.next/standalone/.next/server/app/policies/page/server-reference-manifest.json +14 -14
  52. package/.next/standalone/.next/server/app/policies/page.js +2 -2
  53. package/.next/standalone/.next/server/app/policies/page.js.nft.json +1 -1
  54. package/.next/standalone/.next/server/app/policies/page_client-reference-manifest.js +1 -1
  55. package/.next/standalone/.next/server/app/project/[name]/page/build-manifest.json +3 -3
  56. package/.next/standalone/.next/server/app/project/[name]/page/server-reference-manifest.json +1 -1
  57. package/.next/standalone/.next/server/app/project/[name]/page.js.nft.json +1 -1
  58. package/.next/standalone/.next/server/app/project/[name]/page_client-reference-manifest.js +1 -1
  59. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/build-manifest.json +3 -3
  60. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/react-loadable-manifest.json +2 -2
  61. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/server-reference-manifest.json +2 -2
  62. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page.js.nft.json +1 -1
  63. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page_client-reference-manifest.js +1 -1
  64. package/.next/standalone/.next/server/app/projects/page/build-manifest.json +3 -3
  65. package/.next/standalone/.next/server/app/projects/page/server-reference-manifest.json +1 -1
  66. package/.next/standalone/.next/server/app/projects/page.js.nft.json +1 -1
  67. package/.next/standalone/.next/server/app/projects/page_client-reference-manifest.js +1 -1
  68. package/.next/standalone/.next/server/app/settings/page/build-manifest.json +3 -3
  69. package/.next/standalone/.next/server/app/settings/page/server-reference-manifest.json +4 -4
  70. package/.next/standalone/.next/server/app/settings/page.js.nft.json +1 -1
  71. package/.next/standalone/.next/server/app/settings/page_client-reference-manifest.js +1 -1
  72. package/.next/standalone/.next/server/chunks/{[externals]__0e32-7c._.js → [externals]__1qzqcio._.js} +1 -1
  73. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0_usx0j._.js +3 -0
  74. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0_zk340._.js +3 -0
  75. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0clqfab._.js +3 -0
  76. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0o07qi9._.js +1 -1
  77. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0oy4kxb._.js +3 -0
  78. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0zf034w._.js +3 -0
  79. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0igxt32._.js → [root-of-the-server]__1p8poxd._.js} +2 -2
  80. package/.next/standalone/.next/server/chunks/_0lxbzdq._.js +3 -0
  81. package/.next/standalone/.next/server/chunks/_1ek68ln._.js +6 -5
  82. package/.next/standalone/.next/server/chunks/_1lbh81u._.js +3 -0
  83. package/.next/standalone/.next/server/chunks/_1zuiiy3._.js +3 -0
  84. package/.next/standalone/.next/server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_01r25oi._.js +2 -2
  85. package/.next/standalone/.next/server/chunks/{node_modules_posthog-node_dist_entrypoints_index_node_mjs_04op_ou._.js → node_modules_posthog-node_dist_entrypoints_index_node_mjs_09d5c79._.js} +1 -1
  86. package/.next/standalone/.next/server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_09z9-p7._.js +2 -2
  87. package/.next/standalone/.next/server/chunks/{node_modules_posthog-node_dist_entrypoints_index_node_mjs_0dr20uz._.js → node_modules_posthog-node_dist_entrypoints_index_node_mjs_1d2g73o._.js} +1 -1
  88. package/.next/standalone/.next/server/chunks/package_json_[json]_cjs_1nxcc4v._.js +1 -1
  89. package/.next/standalone/.next/server/chunks/src_hooks_fp-home_ts_09kv0bn._.js +1 -1
  90. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__013jr2b._.js +2 -2
  91. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__01wy8d-._.js +2 -2
  92. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__02npjtd._.js +2 -2
  93. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__07gm3zl._.js +4 -4
  94. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0da85px._.js +2 -2
  95. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0ftmoxc._.js +2 -2
  96. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0oa1lav._.js +1 -1
  97. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0p-5p8u._.js +2 -2
  98. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0s740oi._.js +2 -2
  99. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__14muoc4._.js +3 -0
  100. package/.next/standalone/.next/server/chunks/ssr/{src_hooks_08o7bqo._.js → [root-of-the-server]__15r6r7w._.js} +2 -2
  101. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1p2otjt._.js +2 -2
  102. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1tag8_-._.js +5 -0
  103. package/.next/standalone/.next/server/chunks/ssr/_08x1r5t._.js +1 -1
  104. package/.next/standalone/.next/server/chunks/ssr/{_1oggjel._.js → _0ovx4lz._.js} +1 -1
  105. package/.next/standalone/.next/server/chunks/ssr/_1dkh76z._.js +23 -0
  106. package/.next/standalone/.next/server/chunks/ssr/_1u8-lu2._.js +1 -1
  107. package/.next/standalone/.next/server/chunks/ssr/_1zopuov._.js +1 -1
  108. package/.next/standalone/.next/server/chunks/ssr/app_audit__components_audit-dashboard_tsx_0p9ud47._.js +1 -1
  109. package/.next/standalone/.next/server/chunks/ssr/app_global-error_tsx_1kp6l3x._.js +1 -1
  110. package/.next/standalone/.next/server/chunks/ssr/app_policies_hooks-client_tsx_19dqvpc._.js +1 -1
  111. package/.next/standalone/.next/server/chunks/ssr/app_settings_settings-client_tsx_20lq-mq._.js +1 -1
  112. package/.next/standalone/.next/server/chunks/ssr/node_modules_13n822a._.js +1 -1
  113. package/.next/standalone/.next/server/chunks/ssr/node_modules_posthog-node_dist_entrypoints_index_node_mjs_11bnuzn._.js +2 -2
  114. package/.next/standalone/.next/server/middleware-build-manifest.js +6 -6
  115. package/.next/standalone/.next/server/middleware.js +1 -1
  116. package/.next/standalone/.next/server/pages/404.html +1 -1
  117. package/.next/standalone/.next/server/pages/500.html +1 -1
  118. package/.next/standalone/.next/server/server-reference-manifest.js +1 -1
  119. package/.next/standalone/.next/server/server-reference-manifest.json +19 -19
  120. package/.next/standalone/.next/static/chunks/{1yw71gn8vqco1.js → 00_t-xvc59tkb.js} +2 -2
  121. package/.next/standalone/.next/static/chunks/{3jjmdqqzem21x.js → 07j2u70_3qsx8.js} +1 -1
  122. package/.next/standalone/.next/static/chunks/{2fzxl7n717pbc.js → 0d_re32wscs0b.js} +1 -1
  123. package/.next/standalone/.next/static/chunks/{0ykd_go4oahan.js → 0ds64uculrze8.js} +1 -1
  124. package/.next/standalone/.next/static/chunks/{0nnbtp0w4sxrr.js → 0k_yvjc1yz0pq.js} +1 -1
  125. package/.next/standalone/.next/static/chunks/0lshnlpy1m6bc.js +1 -0
  126. package/.next/standalone/.next/static/chunks/{1da5a_a-3btas.js → 1o0ahew9568ls.js} +1 -1
  127. package/.next/standalone/.next/static/chunks/{1za08zjcctyil.js → 1oz0svxwt9574.js} +2 -2
  128. package/.next/standalone/.next/static/chunks/{29eh4k77otcw6.js → 1q76jk_1_wgjq.js} +1 -1
  129. package/.next/standalone/.next/static/chunks/{2axi5ehjbld9h.js → 2817_8e94ah9z.js} +1 -1
  130. package/.next/standalone/.next/static/chunks/{1nzy5jc_vf9e0.js → 2dbi_x0c8n8fi.js} +1 -1
  131. package/.next/standalone/.next/static/chunks/{1fac8krph-zgp.js → 354-n7p7labpn.js} +1 -1
  132. package/.next/standalone/.next/static/chunks/turbopack-17utl_jw0wj11.js +1 -0
  133. package/.next/standalone/SECURITY.md +18 -3
  134. package/.next/standalone/fp-cloud-cli/CHANGELOG.md +7 -0
  135. package/.next/standalone/fp-cloud-cli/uv.lock +6 -6
  136. package/.next/standalone/node_modules/@next/env/package.json +1 -1
  137. package/.next/standalone/node_modules/next/dist/build/swc/index.js +1 -1
  138. package/.next/standalone/node_modules/next/dist/client/components/segment-cache/cache.js +23 -34
  139. package/.next/standalone/node_modules/next/dist/compiled/next-server/app-page-turbo-experimental.runtime.prod.js +1 -1
  140. package/.next/standalone/node_modules/next/dist/compiled/next-server/app-page-turbo.runtime.prod.js +1 -1
  141. package/.next/standalone/node_modules/next/dist/compiled/next-server/pages-turbo.runtime.prod.js +1 -1
  142. package/.next/standalone/node_modules/next/dist/lib/patch-incorrect-lockfile.js +3 -3
  143. package/.next/standalone/node_modules/next/dist/server/config.js +1 -1
  144. package/.next/standalone/node_modules/next/dist/server/dev/hot-reloader-turbopack.js +2 -2
  145. package/.next/standalone/node_modules/next/dist/server/dev/hot-reloader-webpack.js +1 -1
  146. package/.next/standalone/node_modules/next/dist/server/lib/app-info-log.js +1 -1
  147. package/.next/standalone/node_modules/next/dist/server/lib/start-server.js +1 -1
  148. package/.next/standalone/node_modules/next/dist/telemetry/anonymous-meta.js +1 -1
  149. package/.next/standalone/node_modules/next/dist/telemetry/events/swc-load-failure.js +1 -1
  150. package/.next/standalone/node_modules/next/dist/telemetry/events/version.js +2 -2
  151. package/.next/standalone/node_modules/next/package.json +10 -10
  152. package/.next/standalone/package.json +19 -19
  153. package/.next/standalone/sdk/python/CHANGELOG.md +7 -0
  154. package/.next/standalone/sdk/python/uv.lock +23 -23
  155. package/.next/standalone/server.js +1 -1
  156. package/bin/failproofai.mjs +131 -55
  157. package/dist/cli.mjs +12940 -12627
  158. package/dist/worker.mjs +11 -1
  159. package/package.json +19 -19
  160. package/src/audit/cache.ts +34 -29
  161. package/src/audit/replay.ts +15 -91
  162. package/src/hooks/configure-wizard.ts +16 -48
  163. package/src/hooks/handler.ts +8 -1
  164. package/src/hooks/manager.ts +24 -2
  165. package/src/hooks/pack-cli.ts +572 -43
  166. package/src/hooks/pack-manifest.ts +28 -0
  167. package/src/hooks/pack-store.ts +20 -28
  168. package/.next/standalone/.next/server/chunks/[root-of-the-server]__01eqny5._.js +0 -3
  169. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0neqlu-._.js +0 -3
  170. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0t9oqnn._.js +0 -3
  171. package/.next/standalone/.next/server/chunks/_0bs-v8p._.js +0 -3
  172. package/.next/standalone/.next/server/chunks/_0tovk6q._.js +0 -3
  173. package/.next/standalone/.next/server/chunks/_0trp3yc._.js +0 -3
  174. package/.next/standalone/.next/server/chunks/_185gyk9._.js +0 -3
  175. package/.next/standalone/.next/server/chunks/src_hooks_0xbw3bu._.js +0 -12
  176. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__090sxxw._.js +0 -3
  177. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__192nhvh._.js +0 -5
  178. package/.next/standalone/.next/server/chunks/ssr/_0wb8osu._.js +0 -23
  179. package/.next/standalone/.next/static/chunks/140ip21rqmelt.js +0 -1
  180. package/.next/standalone/.next/static/chunks/turbopack-2vqpa-dts1gy4.js +0 -1
  181. /package/.next/standalone/.next/static/{A7czO1PZdTcNzLGa_H1sm → 0iNzkTsP6rh14Rj5WL17o}/_buildManifest.js +0 -0
  182. /package/.next/standalone/.next/static/{A7czO1PZdTcNzLGa_H1sm → 0iNzkTsP6rh14Rj5WL17o}/_clientMiddlewareManifest.js +0 -0
  183. /package/.next/standalone/.next/static/{A7czO1PZdTcNzLGa_H1sm → 0iNzkTsP6rh14Rj5WL17o}/_ssgManifest.js +0 -0
@@ -1,5 +1,6 @@
1
- module.exports=[97610,e=>{"use strict";var t=e.i(89171),i=e.i(71809),n=e.i(50227),o=e.i(2157),r=e.i(12714),s=e.i(74533),a=e.i(60526);let l=[{name:"sanitize-jwt",description:"Stop Claude from reading JWTs in tool responses",displayTitle:"Redacted JWT tokens from tool output",impact:"Stops the agent from echoing auth tokens it saw in command output.",match:{events:["PostToolUse"]},defaultEnabled:!0,category:"Sanitize"},{name:"sanitize-api-keys",description:"Stop Claude from reading API keys (OpenAI, Anthropic, GitHub, AWS, Stripe, Google) in tool responses",displayTitle:"Redacted API keys from tool output",impact:"Catches OpenAI / Anthropic / GitHub / AWS / Stripe / Google keys before the model sees them.",match:{events:["PostToolUse"]},defaultEnabled:!0,category:"Sanitize",params:{additionalPatterns:{type:"pattern[]",description:"Additional API key patterns to scrub, each with { regex, label }",default:[]}}},{name:"sanitize-connection-strings",description:"Stop Claude from reading database connection strings with embedded credentials in tool responses",displayTitle:"Redacted database connection strings from tool output",impact:"Strips embedded DB credentials before they reach the model context.",match:{events:["PostToolUse"]},defaultEnabled:!0,category:"Sanitize"},{name:"sanitize-private-key-content",description:"Stop Claude from reading PEM private key content in tool responses",displayTitle:"Redacted PEM private keys from tool output",impact:"Prevents private key bodies from being echoed into chat context.",match:{events:["PostToolUse"]},defaultEnabled:!0,category:"Sanitize"},{name:"sanitize-bearer-tokens",displayTitle:"Redacted bearer tokens from tool output",impact:"Strips Authorization: Bearer values before they hit the model.",description:"Stop Claude from reading Authorization Bearer tokens in tool responses",match:{events:["PostToolUse"]},defaultEnabled:!0,category:"Sanitize"},{name:"protect-env-vars",displayTitle:"Tried to dump environment variables to chat",impact:"Env vars often contain secrets; blocking `env` / `printenv` keeps them out of the model context.",description:"Prevent commands that read environment variables",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!0,category:"Environment"},{name:"block-env-files",displayTitle:"Tried to read or write a .env file",impact:"`.env` files routinely contain API keys and DB credentials.",description:"Block reading/writing .env files",match:{events:["PreToolUse"]},defaultEnabled:!0,category:"Environment"},{name:"block-read-outside-cwd",displayTitle:"Tried to read files outside your project directory",impact:"Stops the agent from peeking at neighboring repos or your home directory.",description:"Block file reads outside the session working directory",match:{events:["PreToolUse"],toolNames:["Read","Glob","Grep","Bash"]},defaultEnabled:!1,category:"Environment",params:{allowPaths:{type:"string[]",description:"Absolute paths outside cwd that are allowed to be read",default:[]}}},{name:"block-sudo",displayTitle:"Tried to run a command with sudo",impact:"Sudo gives the agent root — blocked unless explicitly allow-listed.",description:"Block sudo commands",match:{events:["PreToolUse","PermissionRequest"],toolNames:["Bash"]},defaultEnabled:!0,category:"Dangerous Commands",params:{allowPatterns:{type:"string[]",description:"Sudo command patterns to allow, matched token-by-token (e.g. 'sudo systemctl status')",default:[]}}},{name:"block-curl-pipe-sh",displayTitle:"Tried to pipe a downloaded script straight to a shell",impact:"`curl ... | sh` runs unverified remote code on your machine.",description:"Block piping downloads to shell",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!0,category:"Dangerous Commands"},{name:"block-rm-rf",displayTitle:"Tried to recursively delete a system path",impact:"Catches catastrophic `rm -rf /` and Windows equivalents.",description:"Prevent catastrophic deletions",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Dangerous Commands",params:{allowPaths:{type:"string[]",description:"Paths that are allowed to be recursively deleted",default:[]}}},{name:"block-failproofai-commands",displayTitle:"Tried to disable, pause or modify failproofai itself",impact:"An agent that can pause or remove enforcement can switch off every other policy.",description:"Block failproofai CLI commands, self-pause and uninstallation",match:{events:["PreToolUse","PermissionRequest"],toolNames:["Bash"]},defaultEnabled:!0,alwaysOn:!0,category:"Dangerous Commands"},{name:"block-kubectl",displayTitle:"Tried to run a Kubernetes command",impact:"kubectl can change live cluster state — gated unless allow-listed.",description:"Block kubectl commands (Kubernetes cluster mutations)",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"kubectl command patterns to allow, matched token-by-token (e.g. 'kubectl get *', 'kubectl describe *')",default:[]}}},{name:"block-terraform",displayTitle:"Tried to run a Terraform/OpenTofu command",impact:"Terraform mutates real infrastructure — gated unless allow-listed.",description:"Block terraform and tofu (OpenTofu) commands",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"terraform/tofu command patterns to allow (e.g. 'terraform plan', 'terraform validate')",default:[]}}},{name:"block-aws-cli",displayTitle:"Tried to run an AWS CLI command",impact:"AWS CLI can spend money or break prod — gated.",description:"Block aws CLI commands",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"aws CLI command patterns to allow (e.g. 'aws s3 ls *', 'aws sts get-caller-identity')",default:[]}}},{name:"block-gcloud",displayTitle:"Tried to run a Google Cloud command",impact:"gcloud can spend money or break prod — gated.",description:"Block gcloud (Google Cloud) CLI commands",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"gcloud command patterns to allow (e.g. 'gcloud auth list', 'gcloud config list')",default:[]}}},{name:"block-az-cli",displayTitle:"Tried to run an Azure CLI command",impact:"az can spend money or break prod — gated.",description:"Block az (Azure) CLI commands",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"az CLI command patterns to allow (e.g. 'az account show', 'az group list')",default:[]}}},{name:"block-helm",displayTitle:"Tried to run a Helm command",impact:"Helm releases mutate cluster state — gated.",description:"Block helm commands",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"helm command patterns to allow (e.g. 'helm list', 'helm status *')",default:[]}}},{name:"block-gh-pipeline",displayTitle:"Tried to run a privileged GitHub CLI pipeline command",impact:"Catches `gh workflow run`, `gh pr merge`, `gh secret set`, etc.",description:"Block gh CLI pipeline-trigger subcommands (workflow run, run rerun/cancel, pr merge, release create/delete, cache delete, secret set/delete)",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"gh pipeline command patterns to allow (e.g. specific scripted invocations); read-only gh subcommands like 'gh pr view' and 'gh run list' are not matched by this policy",default:[]}}},{name:"block-secrets-write",displayTitle:"Tried to write a secret-key file",impact:"Stops the agent from creating `.pem`, `id_rsa`, `credentials.json`, etc.",description:"Block writing secret key files",match:{events:["PreToolUse"],toolNames:["Write"]},defaultEnabled:!1,category:"Dangerous Commands",params:{additionalPatterns:{type:"string[]",description:"Additional filename patterns (substrings) to block",default:[]}}},{name:"block-push-master",displayTitle:"Tried to push directly to main/master",impact:"Direct pushes to a protected branch bypass review.",description:"Block pushing to main/master",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!0,category:"Git",params:{protectedBranches:{type:"string[]",description:"Branch names to protect from direct pushes",default:["main","master"]}}},{name:"block-force-push",displayTitle:"Tried to force-push",impact:"Force-pushes rewrite history and can clobber teammates' work.",description:"Prevent force-pushing to any branch",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Git"},{name:"block-work-on-main",displayTitle:"Tried to commit or merge on main/master",impact:"Work should land via PR — direct commits skip review.",description:"Block git commits and merges on main/master branch",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Git",params:{protectedBranches:{type:"string[]",description:"Branch names where commits/merges are blocked",default:["main","master"]}}},{name:"warn-git-amend",displayTitle:"Used git commit --amend",impact:"Amending after a push rewrites history that others may have pulled.",description:"Warns before amending git commits, which rewrites history",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Git"},{name:"warn-git-stash-drop",displayTitle:"Tried to drop or clear git stash",impact:"Stash deletions are permanent and silent.",description:"Warns before permanently deleting stashed changes",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Git"},{name:"warn-all-files-staged",displayTitle:"Staged all files with git add -A / .",impact:"Wide stages routinely catch generated files or secrets you didn't intend to commit.",description:"Warns before staging all working tree files with git add -A / . / --all",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Git"},{name:"warn-destructive-sql",displayTitle:"Ran destructive SQL (DROP / TRUNCATE / DELETE without WHERE)",impact:"Easy way to wipe a table by accident.",description:"Warn before executing destructive SQL (DROP/TRUNCATE/DELETE without WHERE) via database clients",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Database"},{name:"warn-schema-alteration",displayTitle:"Altered a database schema column",impact:"ALTER TABLE operations can lock tables and break readers.",description:"Warns before SQL schema changes (ALTER TABLE with column or rename operations)",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Database"},{name:"warn-package-publish",displayTitle:"Tried to publish a package",impact:"Publishes are irreversible — `npm publish` / `cargo publish` shouldn't happen without intent.",description:"Warn before publishing packages to public registries (npm, PyPI, crates.io, RubyGems, etc.)",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Packages & System"},{name:"warn-global-package-install",displayTitle:"Installed a package globally",impact:"`npm i -g`, `cargo install`, `pip --user` pollute your machine outside the project.",description:"Warns before installing packages globally (npm -g, cargo install, etc.)",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Packages & System"},{name:"prefer-package-manager",displayTitle:"Used a non-preferred package manager",impact:"Mixing package managers creates lockfile churn for your team.",description:"Blocks non-preferred package managers and tells Claude to use an allowed one (e.g., uv instead of pip)",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Packages & System",params:{allowed:{type:"string[]",description:"Allowed package manager names (e.g. ['uv', 'bun']). Any detected manager not in this list is blocked.",default:[]},blocked:{type:"string[]",description:"Additional manager names to block beyond the built-in list (e.g. ['pdm', 'pipx']).",default:[]}}},{name:"warn-large-file-write",displayTitle:"Wrote a file larger than the configured threshold",impact:"Catches accidentally large file writes (logs, binaries, model dumps).",description:"Warn before writing files larger than 1MB (configurable via thresholdKb param)",match:{events:["PreToolUse"],toolNames:["Write"]},defaultEnabled:!1,category:"Packages & System",params:{thresholdKb:{type:"number",description:"File size threshold in KB above which a warning is issued",default:1024}}},{name:"warn-background-process",displayTitle:"Started a long-lived background process",impact:"Catches `nohup` / `&` / `screen` / `tmux` / `disown` patterns that the agent often forgets to clean up.",description:"Warns before starting detached or background processes",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Packages & System"},{name:"warn-repeated-tool-calls",displayTitle:"Called the same tool 3+ times with identical arguments",impact:"Usually a sign of a stuck loop burning tokens.",description:"Warn when the same tool is called 3+ times with identical parameters",match:{events:["PreToolUse"]},defaultEnabled:!1,category:"AI Behavior"},{name:"require-commit-before-stop",displayTitle:"Stopped with uncommitted changes",impact:"Work not in a commit is invisible to teammates and easy to lose.",description:"Require all changes to be committed before Claude stops",match:{events:["Stop"]},defaultEnabled:!1,category:"Workflow"},{name:"require-push-before-stop",displayTitle:"Stopped with unpushed commits",impact:"Local-only commits won't trigger CI or be reviewable.",description:"Require all commits to be pushed to remote before Claude stops",match:{events:["Stop"]},defaultEnabled:!1,category:"Workflow",params:{remote:{type:"string",description:"Remote name to push to (default: origin)",default:"origin"},baseBranch:{type:"string",description:"Base branch to compare against (default: main)",default:"main"}}},{name:"require-pr-before-stop",displayTitle:"Stopped without a PR for the branch",impact:"Branches without PRs don't get reviewed.",description:"Require a pull request to exist for the current branch before Claude stops",match:{events:["Stop"]},defaultEnabled:!1,category:"Workflow",params:{baseBranch:{type:"string",description:"Base branch to compare against (default: main)",default:"main"}}},{name:"require-no-conflicts-before-stop",displayTitle:"Stopped with a branch that conflicts with main",impact:"Conflicting branches can't merge — surface them early.",description:"Require the current branch to merge cleanly with the base branch before Claude stops",match:{events:["Stop"]},defaultEnabled:!1,category:"Workflow",params:{baseBranch:{type:"string",description:"Base branch to check for conflicts against (default: main)",default:"main"}}},{name:"require-ci-green-before-stop",displayTitle:"Stopped with failing CI",impact:"Failing CI blocks deploy.",description:"Require CI checks to pass on the current HEAD commit before Claude stops (ignores stale runs on prior commits)",match:{events:["Stop"]},defaultEnabled:!1,category:"Workflow"}];function c(e){return e?{decision:"allow",reason:e}:{decision:"allow"}}function d(e){return{decision:"deny",reason:e}}function p(e){return{decision:"instruct",reason:e}}let u="__FAILPROOFAI_POLICY_REGISTRY__",m="__FAILPROOFAI_POLICY_INDEX_CACHE__",f="failproofai";function h(e){return e.includes("/")?e:`${f}/${e}`}function g(e){globalThis[m]=e}function y(){let e=globalThis;return e[u]||(e[u]=[]),e[u]}function b(e,t,i,n,o=0,r){let s=h(e),a=y(),l=a.findIndex(e=>e.name===s),c={name:s,description:t,fn:i,match:n,priority:o,...r?{params:r}:{}};l>=0?a[l]=c:a.push(c),g(null)}var w=e.i(97348);let k=function(e){let t=e.replaceAll("\\","/");for(let e of[".claude",".codex",".copilot",".cursor",".opencode",".pi",".gemini"]){let i=(0,n.join)((0,a.homedir)(),e).replaceAll("\\","/");if(t===i||t.startsWith(i+"/"))return!0}for(let e of[(0,n.join)(".config","opencode"),(0,n.join)(".local","share","opencode")]){let i=(0,n.join)((0,a.homedir)(),e).replaceAll("\\","/");if(t===i||t.startsWith(i+"/"))return!0}return!1},v=function(e){return!!(/[\\/]\.claude[\\/]settings(?:\.[^/\\]+)?\.json$/.test(e)||/[\\/]\.codex[\\/]hooks\.json$/.test(e)||/[\\/]\.copilot[\\/]hooks[\\/][^/\\]+\.json$/.test(e)||/[\\/]\.github[\\/]hooks[\\/][^/\\]+\.json$/.test(e)||/[\\/]\.cursor[\\/]hooks\.json$/.test(e)||/[\\/]\.opencode[\\/]opencode\.jsonc?$/.test(e)||/[\\/]\.opencode[\\/]plugins[\\/][^/\\]+\.(?:mjs|js|ts)$/.test(e)||/[\\/]\.config[\\/]opencode[\\/]opencode\.jsonc?$/.test(e)||/[\\/]\.config[\\/]opencode[\\/]config\.json$/.test(e)||/[\\/]\.config[\\/]opencode[\\/]plugins[\\/][^/\\]+\.(?:mjs|js|ts)$/.test(e)||/[\\/]\.pi[\\/](?:agent[\\/])?settings\.json$/.test(e)||/[\\/]\.pi[\\/](?:agent[\\/])?extensions[\\/]/.test(e)||/[\\/]\.gemini[\\/]settings\.json$/.test(e)||/[\\/]\.gemini[\\/]config[\\/]hooks\.json$/.test(e))};function N(e){return e.toolInput?.command??""}function S(e){return e.toolInput?.file_path??""}function $(e){return e.trim().split(/\s+/).map(e=>e.replace(/^['"]|['"]$/g,""))}let T=new Set(["&&","||","|",";"]),E=/[;&<>`$()\\]/,C=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/,A=[[/sk-ant-[A-Za-z0-9\-_]{20,}/,"Anthropic API key"],[/sk-proj-[A-Za-z0-9\-_]{20,}/,"OpenAI project API key"],[/sk-[A-Za-z0-9]{20,}/,"OpenAI API key"],[/ghp_[A-Za-z0-9]{36}/,"GitHub personal access token"],[/github_pat_[A-Za-z0-9_]{82}/,"GitHub fine-grained token"],[/AKIA[A-Z0-9]{16}/,"AWS access key ID"],[/sk_live_[A-Za-z0-9]{24,}/,"Stripe live secret key"],[/sk_test_[A-Za-z0-9]{24,}/,"Stripe test secret key"],[/AIza[0-9A-Za-z\-_]{35}/,"Google API key"]],P=/(?:postgresql|postgres|mysql|mongodb(?:\+srv)?|redis|amqps?|smtps?):\/\/[^@\s]+@/,I=/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----/,x=/Authorization:\s*Bearer\s+[A-Za-z0-9\-._~+/]{20,}/i;[...A];let R=/\b(?:psql|mysql|sqlite3|pgcli|clickhouse-client)\b/,O=/\b(?:DROP\s+(?:TABLE|DATABASE|SCHEMA)|TRUNCATE\b)/i,_=/\bDELETE\s+FROM\b/i,j=/\bWHERE\b/i,B=/\bALTER\s+TABLE\b[\s\S]*\b(?:DROP\s+COLUMN|ADD\s+COLUMN|RENAME\s+(?:COLUMN|TO)|MODIFY\s+COLUMN)\b/i,D=/(?:npm\s+publish|bun\s+publish|pnpm\s+publish|yarn\s+npm\s+publish|twine\s+upload|poetry\s+publish|cargo\s+publish|gem\s+push)\b/,W=/(?:^|\s|;|&&|\|\|)(?:env|printenv)(?:\s|$|;|&&|\|)/,M=/echo\s+.*\$\{?[A-Za-z_]/,U=/(?:^|\s|;|&&|\|\|)export\s+\w+/,z=/\$env:[A-Za-z_]/i,L=/(?:Get-ChildItem|dir|gci|ls)\s+Env:/i,F=/\[Environment\]::GetEnvironment/i,q=/echo\s+%[A-Za-z_]/i,H=/(?:^|[\\/])\.env(?:\.|$)/,J=/\.env(?:\b|\s|$|\.)/,G=/Start-Process\s+.*-Verb\s+RunAs/i,Z=/(?:^|;|&&|\|\|)\s*runas\s/i,Y=/(?:curl|wget)\s.*\|\s*(?:sh|bash|zsh|dash|ksh|csh|tcsh|fish|ash)\b/,K=/[;&|\n\r(){}`]+/,Q=new Set(["npx","bunx","pnpx","npm","pnpm","yarn","dlx","exec","run","eval","node","bun","deno","env","command","builtin","nohup","setsid","time","timeout","nice","stdbuf","xargs","sudo","doas","sh","bash","zsh","dash","ksh","fish","ash"]),V=/(?:^|\/)failproofai[^/]*$/,X=/failproofai\/(?:dist\/(?:cli|index)\.mjs|bin\/failproofai\.mjs)$/,ee=/^(?:config|configure|setup)$/,et=/^--pause(?:=|$)/,ei=/^[A-Za-z_][A-Za-z0-9_]*=/,en=/^\d+[a-z]*$/i;function eo(e){let t=e.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,"$$$1"),i=null,n=new Set;for(let[,e,i]of t.matchAll(/(?:^|[\s;&|])([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|]+)/g)){let t=i.replace(/^["']|["']$/g,"");(V.test(t)||X.test(t))&&n.add(e)}let o=e=>{let t=/^\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?$/.exec(e);return!!t&&n.has(t[1])};for(let e of t.split(K)){let t=e.split(/\s+/).filter(Boolean),n=0;for(;n<t.length;){let e=t[n];if(!(ei.test(e)||e.startsWith("-")||e.startsWith(">")||e.startsWith("<")||en.test(e)||Q.has(e.slice(e.lastIndexOf("/")+1))))break;n++}if(n>=t.length||!V.test(t[n])&&!X.test(t[n])&&!o(t[n]))continue;let r=t.slice(n+1),s=r.findIndex(e=>ee.test(e));if(-1!==s&&r.slice(s+1).some(e=>et.test(e)))return"pause";i="cli"}return i}let er=/(?:Invoke-WebRequest|iwr|Invoke-RestMethod|irm)\s+.*\|\s*(?:Invoke-Expression|iex)/i,es=/^-[a-zA-Z]*f[a-zA-Z]*$/,ea=["--force-with-lease","--force-if-includes"],el=/\.(?:pem|key)$/,ec=/id_rsa/,ed=/credentials/,ep=/git\s+(commit|merge|rebase|cherry-pick)\b/,eu=/\b(?:rm|unlink|shred|mv|truncate)\b[^;&|]*\.failproofai(?:\/|\b)/,em=/(?:npm\s+(?:uninstall|remove|un|r)\s.*failproofai|bun\s+remove\s.*failproofai|yarn\s+global\s+remove\s+failproofai|pnpm\s+(?:remove|uninstall|un)\s.*failproofai)/,ef=/\bgit\s+commit\b.*--amend\b/,eh=/\bgit\s+stash\s+(?:drop|clear)\b/,eg=/\bgit\s+add\s+(?:-A\b|--all\b|\.(?:\s|$|;|&&|\|\|))/,ey=/\bnpm\s+(?:install|i)\b(?=.*(?:\s-g\b|--global\b))/,eb=/\byarn\s+global\s+add\b/,ew=/\bpnpm\s+(?:add|install|i)\b(?=.*(?:\s-g\b|--global\b))/,ek=/\bbun\s+(?:install|add)\b(?=.*(?:\s-g\b|--global\b))/,ev=/\bcargo\s+install\b/,eN=/\bpip(?:3)?\s+install\b(?=.*(?:--user\b|--break-system-packages\b))/,eS={pip:[/\bpip\b/,/\bpip3\b/,/\bpython3?\s+-m\s+pip\b/],npm:[/\bnpm\b/,/\bnpx\b/],yarn:[/\byarn\b/],pnpm:[/\bpnpm\b/,/\bpnpx\b/],bun:[/\bbun\b/,/\bbunx\b/],uv:[/\buv\b/],poetry:[/\bpoetry\b/],pipenv:[/\bpipenv\b/],conda:[/\bconda\b/],cargo:[/\bcargo\b/]},e$=/\bnohup\s+\S/,eT=/\bscreen\s+-[A-Za-z]*d[A-Za-z]*\b/,eE=/\btmux\s+(?:new-session|new)\b[^|&;]*-d\b/,eC=/\bdisown\b/,eA=/(?<![&|])\s?&\s*(?:$|#|;)/,eP=/(?:^|[;\n]|&&|\|\|?|&)\s*kubectl(?:\s|$)/,eI=/(?:^|[;\n]|&&|\|\|?|&)\s*(?:terraform|tofu)(?:\s|$)/,ex=/(?:^|[;\n]|&&|\|\|?|&)\s*aws(?:\s|$)/,eR=/(?:^|[;\n]|&&|\|\|?|&)\s*gcloud(?:\s|$)/,eO=/(?:^|[;\n]|&&|\|\|?|&)\s*az(?:\s|$)/,e_=/(?:^|[;\n]|&&|\|\|?|&)\s*helm(?:\s|$)/,ej=/(?:^|[;\n]|&&|\|\|?|&)\s*gh\s+(?:workflow\s+(?:run|enable|disable)|run\s+(?:rerun|cancel)|pr\s+merge|release\s+(?:create|delete)|cache\s+delete|secret\s+(?:set|delete))\b/,eB=new Map;function eD(e){try{let t=function(e){try{return(0,o.statSync)((0,n.join)(e,".git","HEAD")).mtimeMs}catch{return null}}(e),i=eB.get(e);if(i&&null!==t&&i.headMtimeMs===t)return i.branch||null;let r=(0,s.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}).trim();return null!==t&&(eB.size>=500&&eB.clear(),eB.set(e,{branch:r,headMtimeMs:t})),r||null}catch{return null}}function eW(e,t){let i=$(e),n=$(t);return!(i.length<n.length||i.some(e=>T.has(e))||i.some(e=>E.test(e)))&&n.every((e,t)=>"*"===e||e===i[t])}let eM=/^-{1,2}c$/;function eU(e){return e.split(/&&|\|\||[|;\n]/).map(e=>e.trim()).filter(e=>/^git\s+push\s/.test(e)).map(e=>e.replace(/^git\s+push\s+/,""))}let ez=/^(?:~[A-Za-z0-9_.-]*|\$HOME|\$\{HOME\})(?=$|\/)/,eL=/^(?:\/\S*\/)?rm$/,eF=/^(?:\/\S*\/)?find$/,eq=/^-(?:exec|execdir|ok|okdir)$/,eH=/^-(?:[HLP]|D|O\d*)$/,eJ=/^(?:-|\\?[(!])/,eG=["/tmp","/var/tmp"];function eZ(e){let t=e.match(/^(?:~|\$HOME|\$\{HOME\})(?=$|\/)/);return t?(0,a.homedir)()+e.slice(t[0].length):e}function eY(e){return e.replace(/\/\*$/,"").replace(/\/+$/,"")}function eK(e){let t=e.replace(/^['"]|['"]$/g,"");if(""===t)return!1;let i=t.match(ez);if(!i&&/^[$`]/.test(t))return!0;let n=i?t.slice(i[0].length):t.startsWith("/")?t:null;if(null===n)return!1;let o=eY(n).split("/").filter(Boolean);return!(!i&&eG.some(e=>`/${o.join("/")}`.startsWith(`${e}/`)))&&o.length<=2}function eQ(e){let t=$(e),i=t.findIndex(e=>eF.test(e));if(i>=0){let e=t.slice(i+1),n=e.findIndex(e=>eq.test(e));if(e.includes("-delete")||n>=0&&eL.test(e[n+1]??"")){let t=0;for(;t<e.length&&eH.test(e[t]);)t+="-D"===e[t]?2:1;let i=e.slice(t),n=i.findIndex(e=>eJ.test(e));return n<0?i:i.slice(0,n)}}let n=t.findIndex(e=>eL.test(e));if(n>=0){let e=t.slice(n+1),i=e.filter(e=>/^-[^-]/.test(e)).join(""),o=e.filter(e=>/^--/.test(e)),r=/r/i.test(i)||o.some(e=>/^--recursive$/i.test(e)),s=/f/.test(i)||o.some(e=>/^--force$/i.test(e));if(r&&s)return e.filter(e=>!e.startsWith("-"))}return null}function eV(e){return e.split(/&&|\|\||[|;\n]/).map(e=>e.trim()).filter(e=>""!==e)}let eX=/(?:^|;|&&|\|\||\|)\s*(?:ls|find|cat|head|tail|less|more|wc|file|stat|tree|du)\s/;function e0(e,t,i){if("Bash"!==e.toolName)return c();let n=N(e);return!t.test(n)||(e.params?.allowPatterns??[]).some(e=>eW(n,e))?c():d(i)}let e1=/\s*(?:&&|\|\||\||;)\s*/;function e3(e){return e.session?.permissionMode==="plan"}let e6={"sanitize-jwt":function(e){let t=JSON.stringify(e.payload);return C.test(t)?{decision:"deny",reason:"JWT token detected in tool output",message:"[REDACTED: JWT token removed by failproofai]"}:c()},"sanitize-api-keys":function(e){let t=JSON.stringify(e.payload);for(let[e,i]of A)if(e.test(t))return{decision:"deny",reason:`${i} detected in tool output`,message:`[REDACTED: ${i} removed by failproofai]`};for(let{regex:i,label:n}of e.params?.additionalPatterns??[])try{if(new RegExp(i).test(t))return{decision:"deny",reason:`${n} detected in tool output`,message:`[REDACTED: ${n} removed by failproofai]`}}catch{(0,w.hookLogWarn)(`additionalPatterns: invalid regex "${i}", skipping`)}return c()},"sanitize-connection-strings":function(e){let t=JSON.stringify(e.payload);return P.test(t)?{decision:"deny",reason:"Database connection string with credentials detected in tool output",message:"[REDACTED: connection string removed by failproofai]"}:c()},"sanitize-private-key-content":function(e){let t=JSON.stringify(e.payload);return I.test(t)?{decision:"deny",reason:"Private key content detected in tool output",message:"[REDACTED: private key content removed by failproofai]"}:c()},"sanitize-bearer-tokens":function(e){let t=JSON.stringify(e.payload);return x.test(t)?{decision:"deny",reason:"Bearer token detected in tool output",message:"[REDACTED: Bearer token removed by failproofai]"}:c()},"protect-env-vars":function(e){if("Bash"!==e.toolName)return c();let t=N(e);return W.test(t)?d("Command reads environment variables"):M.test(t)?d("Command echoes environment variable"):U.test(t)?d("Command exports environment variable"):z.test(t)?d("Command reads environment variable via PowerShell"):L.test(t)?d("Command reads environment variables via PowerShell"):F.test(t)?d("Command reads environment variable via .NET"):q.test(t)?d("Command echoes environment variable via cmd"):c()},"block-env-files":function(e){let t=N(e),i=S(e);return i&&H.test(i)?d("Access to .env file blocked"):"Bash"===e.toolName&&J.test(t)?d("Command references .env file"):c()},"block-read-outside-cwd":function(e){let t=process.env.CLAUDE_PROJECT_DIR||e.session?.cwd;if(!t)return c();let i=e.params?.allowPaths??[];if("Bash"===e.toolName){let o=N(e);if(!eX.test(o))return c();let r=function(e){let t,i=[],o=/(?<![a-zA-Z0-9_.\-~\\*?:=])(?:~\/[^\s;|&"'()\[\]{}]*|~(?=\s|$|[;|&"'()\[\]{}])|\/[^\s;|&"'()\[\]{}]*)/g;function r(e){let t;for(o.lastIndex=0;null!==(t=o.exec(e));){let e=t[0];"~"===e?e=(0,a.homedir)():e.startsWith("~/")&&(e=(0,n.join)((0,a.homedir)(),e.slice(2))),i.push(e)}}let s=e.length,l=!1,c=!1;for(let t=0;t<e.length;t++){let i=e[t];if('"'!==i||c)if("'"!==i||l){if("|"===i&&!l&&!c){s=t;break}}else c=!c;else l=!l}let d=e.slice(0,s),p=/"([^"]*)"|'([^']*)'/g;for(;null!==(t=p.exec(d));){let e=t[1]??t[2]??"";/[*?\[\]^$+()\\]/.test(e)||r(e)}return r(e.replace(/"[^"]*"/g,e=>" ".repeat(e.length)).replace(/'[^']*'/g,e=>" ".repeat(e.length))),i}(o),s=t.endsWith("/")?t:t+"/";for(let e of r){let o=(0,n.resolve)(t,e);if(v(o))return d(`Reading agent settings file blocked: ${o}`);if(!k(o)&&"/dev/null"!==o&&o!==t&&!o.startsWith(s)){if(i.some(e=>o===e||o.startsWith(e.endsWith("/")?e:e+"/")))continue;return d(`Bash read outside project directory blocked: ${o}`)}}return c()}let o=S(e),r=e.toolInput?.path??"",s=o||r;if(!s)return c();let l=(0,n.resolve)(t,s);if(v(l))return d(`Reading agent settings file blocked: ${l}`);if(k(l)||"/dev/null"===l)return c();let p=t.endsWith("/")?t:t+"/";return l===t||l.startsWith(p)?c():i.some(e=>l===e||l.startsWith(e.endsWith("/")?e:e+"/"))?c():d(`Access outside project directory blocked: ${l}`)},"block-sudo":function(e){if("Bash"!==e.toolName)return c();let t=N(e).trimStart();return function e(t,i=0){for(let n of function(e){let t=[],i=[],n="",o=null,r=()=>{n&&i.push(n),n=""},s=()=>{r(),i.length&&t.push(i),i=[]};for(let t=0;t<e.length;t++){let i=e[t];if(o){if("\\"===i&&'"'===o&&t+1<e.length){n+=e[++t];continue}if(i===o){o=null;continue}n+=i;continue}if("\\"===i&&t+1<e.length){n+=e[++t];continue}if('"'===i||"'"===i){o=i;continue}if(/\s/.test(i)){r();continue}if(/[;&|\n\r(){}`]/.test(i)){s();continue}n+=i}return s(),t}(t)){let t=0;for(;t<n.length;){let o=n[t],r=o.slice(o.lastIndexOf("/")+1);if("sudo"===r||"doas"===r)return!0;if(!(ei.test(o)||o.startsWith("-")||o.startsWith(">")||o.startsWith("<")||en.test(o)||Q.has(r)))break;if(eM.test(o)&&i<3&&t+1<n.length&&e(n[t+1],i+1))return!0;t++}}return!1}(t)?(e.params?.allowPatterns??[]).some(e=>eW(t,e))?c():d("sudo commands are blocked"):G.test(t)?d("Elevated process launch is blocked"):Z.test(t)?d("runas elevation is blocked"):c()},"block-curl-pipe-sh":function(e){if("Bash"!==e.toolName)return c();let t=N(e);return Y.test(t)?d("Piping downloads to shell is blocked"):er.test(t)?d("Piping downloads to Invoke-Expression is blocked"):c()},"block-rm-rf":function(e){if("Bash"!==e.toolName)return c();let t=N(e);return eV(t).some(e=>{let t=eQ(e);return null!==t&&t.some(eK)})?!function(e,t){if(0===t.length)return!1;let i=t.map(e=>eY(eZ(e))||"/"),n=!1;for(let o of eV(e)){let e=eQ(o);if(null!==e)for(let r of(n=!0,e)){let e=eY(eZ(r))||"/";if(!i.some(t=>e===t||e.startsWith(t+"/"))&&!t.some(e=>{let t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return RegExp(`${t}(?:[/"'\\s/*]|$)`).test(o)}))return!1}}return n}(t,e.params?.allowPaths??[])?d("Catastrophic deletion blocked"):c():/Remove-Item\s+.*-Recurse.*-Force.*(?:[A-Z]:\\(?:\s|$)|\\\*)/i.test(t)||/(?:rd|rmdir)\s+\/s\s+\/q\s+[A-Z]:\\/i.test(t)?d("Catastrophic deletion blocked"):c()},"block-failproofai-commands":function(e){if("Bash"!==e.toolName)return c();let t=N(e),i=t.replace(/\\\r?\n/g,"").replace(/\$'((?:[^'\\]|\\.)*)'/g,(e,t)=>t.replace(/\\(x[0-9A-Fa-f]{1,2}|u[0-9A-Fa-f]{1,4}|U[0-9A-Fa-f]{1,8}|[0-7]{1,3}|.)/g,(e,t)=>{try{if("x"===t[0])return String.fromCharCode(parseInt(t.slice(1),16));if("u"===t[0]||"U"===t[0])return String.fromCodePoint(parseInt(t.slice(1),16));if(/^[0-7]+$/.test(t))return String.fromCharCode(parseInt(t,8))}catch{return t}return({a:"\x07",b:"\b",e:"\x1b",f:"\f",n:"\n",r:"\r",t:" ",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"})[t]??t})).replace(/\\(.)/g,"$1").replace(/['"]/g,""),n=eo(t)??eo(i);return"pause"===n?d("Pausing failproofai enforcement is a human action, not an agent one. If a policy is blocking legitimate work, say so and let the operator decide."):"cli"===n?d("Running failproofai CLI commands is blocked"):em.test(t)||em.test(i)?d("Uninstalling failproofai is blocked"):eu.test(t)||eu.test(i)?d("Deleting or moving failproofai's own state would switch enforcement off. If a policy is blocking legitimate work, say so and let the operator decide."):c()},"block-kubectl":function(e){return e0(e,eP,"kubectl commands are blocked")},"block-terraform":function(e){return e0(e,eI,"terraform/tofu commands are blocked")},"block-aws-cli":function(e){return e0(e,ex,"aws CLI commands are blocked")},"block-gcloud":function(e){return e0(e,eR,"gcloud commands are blocked")},"block-az-cli":function(e){return e0(e,eO,"az (Azure) CLI commands are blocked")},"block-helm":function(e){return e0(e,e_,"helm commands are blocked")},"block-gh-pipeline":function(e){return e0(e,ej,"gh pipeline-trigger commands are blocked")},"block-secrets-write":function(e){if("Write"!==e.toolName)return c();let t=S(e);if(el.test(t)||ec.test(t)||ed.test(t))return d("Writing secret key files is blocked");for(let i of e.params?.additionalPatterns??[])if(t.includes(i))return d(`Writing blocked file pattern: ${i}`);return c()},"block-push-master":function(e){if("Bash"!==e.toolName)return c();let t=e.params?.protectedBranches??["main","master"];if(0===t.length)return c();let i=eU(N(e)),n=RegExp(`\\b(?:${t.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|")})\\b`);return i.some(e=>n.test(e))?d(`Pushing to ${t.join("/")} is blocked`):c()},"block-force-push":function(e){if("Bash"!==e.toolName)return c();for(let t of eU(N(e))){let e=!1;for(let i of t.split(/\s+/)){if("--"===i){e=!0;continue}if(!e&&function(e){return"--force"===e||!ea.some(t=>e.startsWith(t))&&(!!e.startsWith("--force")||es.test(e))}(i))return d("Force-pushing is blocked")}}return c()},"block-work-on-main":function(e){if("Bash"!==e.toolName)return c();let t=N(e).match(ep);if(!t)return c();let i=e.session?.cwd;if(!i)return c();let n=eD(i);return n&&(e.params?.protectedBranches??["main","master"]).includes(n)?d(`Git ${t[1]} on ${n} is blocked. Create a feature branch first.`):c()},"warn-git-amend":function(e){if("Bash"!==e.toolName)return c();let t=N(e);return ef.test(t)?p("STOP: This command amends the last commit, which rewrites git history. If this commit has already been pushed to a shared branch, this will cause divergence for other contributors. Confirm with the user before executing."):c()},"warn-git-stash-drop":function(e){if("Bash"!==e.toolName)return c();let t=N(e);return eh.test(t)?p("STOP: This command permanently deletes stashed changes (git stash drop/clear). Stash entries cannot be recovered after deletion. Confirm with the user before executing."):c()},"warn-all-files-staged":function(e){if("Bash"!==e.toolName)return c();let t=N(e);return eg.test(t)?p("STOP: This command stages all files in the working tree (git add -A / --all / .). This may inadvertently include build artifacts, generated files, or sensitive files not covered by .gitignore. Confirm with the user before executing."):c()},"warn-destructive-sql":function(e){if("Bash"!==e.toolName)return c();let t=N(e);return R.test(t)&&(O.test(t)||_.test(t)&&!j.test(t))?p("STOP: This command contains destructive SQL (DROP/TRUNCATE/DELETE). Confirm with the user before executing."):c()},"warn-schema-alteration":function(e){if("Bash"!==e.toolName)return c();let t=N(e);return R.test(t)&&B.test(t)?p("STOP: This command contains a schema-altering SQL statement (ALTER TABLE with column or rename operation). Schema changes on production databases are irreversible or disruptive. Confirm with the user before executing."):c()},"warn-package-publish":function(e){if("Bash"!==e.toolName)return c();let t=N(e);return D.test(t)?p("STOP: This command publishes a package to a public registry. Confirm with the user that this is intentional."):c()},"warn-global-package-install":function(e){if("Bash"!==e.toolName)return c();let t=N(e);return ey.test(t)||eb.test(t)||ew.test(t)||ek.test(t)||ev.test(t)||eN.test(t)?p("STOP: This command installs a package globally, which modifies the system-wide environment outside the project. This can conflict with other projects or system tools. Confirm with the user before executing."):c()},"prefer-package-manager":function(e){if("Bash"!==e.toolName)return c();let t=N(e);if(!t)return c();let i=e.params?.allowed??[];if(0===i.length)return c();let n=new Set(i.map(e=>e.toLowerCase())),o=e.params?.blocked??[],r=i.join(", ");for(let e of t.split(e1)){let t=e.trim();if(!t)continue;let i=!1;for(let e of n){let n=eS[e];if(n){for(let e of n)if(e.test(t)){i=!0;break}if(i)break}}if(!i){for(let[e,i]of Object.entries(eS))if(!n.has(e)){for(let n of i)if(n.test(t))return d(`"${e}" is not an allowed package manager. Allowed package managers for this project: ${r}. Rewrite this command using an allowed package manager.`)}for(let e of o){let i=e.toLowerCase();if(!n.has(i)&&RegExp(`\\b${i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`).test(t))return d(`"${i}" is not an allowed package manager. Allowed package managers for this project: ${r}. Rewrite this command using an allowed package manager.`)}}}return c()},"warn-large-file-write":function(e){if("Write"!==e.toolName)return c();let t=e.toolInput?.content;if("string"!=typeof t)return c();let i=e.params?.thresholdKb??1024;return t.length>1024*i?p(`STOP: You are writing a file larger than ${i}KB (${Math.round(t.length/1024)}KB). This is unusually large. Confirm this is intentional before proceeding.`):c()},"warn-background-process":function(e){if("Bash"!==e.toolName)return c();let t=N(e);return e$.test(t)||eT.test(t)||eE.test(t)||eC.test(t)||eA.test(t)?p("STOP: This command starts a background or detached process (nohup, screen -d, tmux -d, or trailing &). Background processes persist after Claude's session and may be difficult to track or stop. Confirm with the user before executing."):c()},"warn-repeated-tool-calls":async function e(e){let t=e.session?.transcriptPath;if(!t||!e.toolName||!e.toolInput)return c();let i=`${t}.tool-calls.json`,n=JSON.stringify({tool:e.toolName,input:e.toolInput}),o={};try{let e=await (0,r.readFile)(i,"utf8");o=JSON.parse(e)}catch{}let s=o[n]??0;if(s>=3)return p(`STOP: You have already called ${e.toolName} ${s} times with identical parameters. This is wasteful and unproductive. Do NOT repeat this call — use a different approach or ask the user for clarification.`);o[n]=s+1;try{let e=JSON.stringify(o);e.length<=65536&&await (0,r.writeFile)(i,e,"utf8")}catch{}return c()},"require-commit-before-stop":function(e){if(e3(e))return c("Plan mode — no changes made, skipping commit check.");let t=e.session?.cwd;if(!t)return c("No working directory available, skipping commit check.");try{if((0,s.execSync)("git status --porcelain",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().length>0)return d("You have uncommitted changes in the working directory. Commit all changes now.");return c("All changes are committed.")}catch{return c("Not a git repository, skipping commit check.")}},"require-push-before-stop":function(e){if(e3(e))return c("Plan mode — no changes made, skipping push check.");let t=e.session?.cwd;if(!t)return c("No working directory available, skipping push check.");try{if(!(0,s.execSync)("git remote",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}).trim())return c("No git remote configured, skipping push check.");let i=e.params?.remote??"origin",n=eD(t);if(!n||"HEAD"===n)return c("Detached HEAD, skipping push check.");let o=e.params?.baseBranch??"main";if(n===o)return c(`On base branch "${o}", skipping push check.`);try{if(!(0,s.execFileSync)("git",["log",`${i}/${o}..HEAD`,"--oneline"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim())return c(`No commits ahead of ${i}/${o}, skipping push check.`);if(!(0,s.execFileSync)("git",["diff","--stat",`${i}/${o}`,"HEAD"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim())return c(`No file changes compared to ${i}/${o}, skipping push check.`)}catch{}let r=!1;try{(0,s.execFileSync)("git",["rev-parse","--verify",`${i}/${n}`],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}),r=!0}catch{}if(!r)return d(`Branch "${n}" has not been pushed to remote "${i}". Run now: git push -u ${i} ${n}`);let a=(0,s.execFileSync)("git",["log",`${i}/${n}..HEAD`,"--oneline"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim();if(a.length>0){let e=a.split("\n").length;return d(`You have ${e} unpushed commit${e>1?"s":""} on branch "${n}". Run now: git push`)}return c(`All commits pushed to "${i}".`)}catch{return c("Could not check push status, skipping.")}},"require-pr-before-stop":function(e){if(e3(e))return c("Plan mode — no changes made, skipping PR check.");let t=e.session?.cwd;if(!t)return c("No working directory available, skipping PR check.");try{let i;try{(0,s.execSync)("gh --version",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3})}catch{return c("GitHub CLI (gh) not installed, skipping PR check.")}let n=eD(t);if(!n||"HEAD"===n)return c("Detached HEAD, skipping PR check.");let o=e.params?.baseBranch??"main";if(n===o)return c(`On base branch "${o}", skipping PR check.`);try{if(!(0,s.execFileSync)("git",["log",`origin/${o}..HEAD`,"--oneline"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim())return c(`No commits ahead of origin/${o}, skipping PR check.`);if(!(0,s.execFileSync)("git",["diff","--stat",`origin/${o}`,"HEAD"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim())return c(`No file changes compared to origin/${o}, skipping PR check.`)}catch{}try{i=(0,s.execSync)("gh pr view --json number,url,state",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:15e3}).trim()}catch{return d(`No pull request found for branch "${n}". Run now: gh pr create`)}let r=JSON.parse(i);if("OPEN"===r.state)return c(`PR #${r.number} exists: ${r.url}`);if("MERGED"===r.state)return c(`PR #${r.number} was merged: ${r.url}. Switch off this branch (e.g. 'git checkout ${o} && git pull') before stopping again.`);return d(`Pull request for branch "${n}" is ${r.state.toLowerCase()}. Run now: gh pr create`)}catch{return c("Could not check PR status, skipping.")}},"require-no-conflicts-before-stop":function(e){let t,i;if(e3(e))return c("Plan mode — no changes made, skipping conflict check.");let n=e.session?.cwd;if(!n)return c("No working directory available, skipping conflict check.");let o=eD(n);if(!o||"HEAD"===o)return c("Detached HEAD, skipping conflict check.");let r=e.params?.baseBranch??"main";if(o===r)return c(`On base branch "${r}", skipping conflict check.`);try{(0,s.execSync)("gh --version",{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3})}catch{return c("gh CLI not installed, skipping conflict check.")}try{t=(0,s.execSync)("gh pr view --json mergeable,number,url,state",{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:15e3}).trim()}catch{return c("No pull request found for branch, skipping conflict check.")}try{i=JSON.parse(t)}catch{return c("Could not parse gh pr view output, skipping conflict check.")}if("OPEN"!==i.state)return c(`PR #${i.number} is ${i.state.toLowerCase()}; skipping conflict check.`);try{(0,s.execFileSync)("git",["rev-parse","--verify",`origin/${r}`],{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}),(0,s.execFileSync)("git",["log",`origin/${r}..HEAD`,"--oneline"],{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim()&&(0,s.execFileSync)("git",["merge-tree","--write-tree","--name-only",`origin/${r}`,"HEAD"],{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:1e4})}catch(e){if(1===e.status){let t=("string"==typeof e.stdout?e.stdout:e.stdout?.toString("utf8")??"").trim().split("\n"),i=[];for(let e=1;e<t.length;e++){let n=t[e];if(""===n)break;i.push(n)}let n=i.length?i.join(", "):"one or more files";return d(`Branch "${o}" has merge conflicts with ${r} in: ${n}. Rebase or merge origin/${r} now and resolve the conflicts.`)}}return"CONFLICTING"===i.mergeable?d(`PR #${i.number} has merge conflicts per GitHub (${i.url}). Rebase or merge origin/${r} now and resolve the conflicts.`):"UNKNOWN"===i.mergeable?d(`GitHub is still computing mergeability for PR #${i.number} (${i.url}). Wait ~10 seconds, then re-check with \`gh pr view --json mergeable\` before attempting to stop again.`):c(`PR #${i.number} merges cleanly per GitHub.`)},"require-ci-green-before-stop":function(e){if(e3(e))return c("Plan mode — no changes made, skipping CI check.");let t=e.session?.cwd;if(!t)return c("No working directory available, skipping CI check.");try{try{(0,s.execSync)("gh --version",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3})}catch{return c("GitHub CLI (gh) not installed, skipping CI check.")}let e=eD(t);if(!e||"HEAD"===e)return c("Detached HEAD, skipping CI check.");let i=function(e){try{return(0,s.execSync)("git rev-parse HEAD",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}).trim()||null}catch{return null}}(t),n=[];try{let o=(0,s.execFileSync)("gh",["run","list","--branch",e,"--limit","20","--json","status,conclusion,name,headSha"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:15e3}).trim();if(o&&"[]"!==o){let e=JSON.parse(o),t=i?e.filter(e=>e.headSha===i):e,r=new Set;n=t.filter(e=>!r.has(e.name)&&(r.add(e.name),!0))}}catch{}let o=[],r=[];i&&(o=function(e,t){try{let i=(0,s.execFileSync)("gh",["api",`repos/{owner}/{repo}/commits/${t}/check-runs`,"--jq",'.check_runs | map(select(.app.slug != "github-actions")) | map({name: .name, status: .status, conclusion: (.conclusion // "")})'],{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:15e3}).trim();if(!i||"[]"===i)return[];return JSON.parse(i)}catch{return[]}}(t,i),r=function(e,t){try{let i=(0,s.execFileSync)("gh",["api",`repos/{owner}/{repo}/commits/${t}/statuses`,"--jq","map({name: .context, state: .state}) | unique_by(.name)"],{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:15e3}).trim();if(!i||"[]"===i)return[];return JSON.parse(i).map(e=>({name:e.name,status:"pending"===e.state?"in_progress":"completed",conclusion:"pending"===e.state?"":"success"===e.state?"success":"failure"}))}catch{return[]}}(t,i));let a=[...n,...o,...r];if(0===a.length)return c(`No CI runs found for branch "${e}".`);let l=a.filter(e=>"completed"===e.status&&"success"!==e.conclusion&&"skipped"!==e.conclusion&&"cancelled"!==e.conclusion&&"neutral"!==e.conclusion);if(l.length>0){let t=l.map(e=>`"${e.name}"`).join(", ");return d(`CI checks are failing on branch "${e}": ${t}. Fix the failing checks now.`)}let p=a.filter(e=>"in_progress"===e.status||"queued"===e.status||"waiting"===e.status);if(p.length>0){let t=p.map(e=>`"${e.name}"`).join(", ");return d(`CI checks are still running on branch "${e}": ${t}. Wait for all checks to complete, then verify they pass.`)}return c(`All CI checks passed on branch "${e}".`)}catch{return c("Could not check CI status, skipping.")}}},e9=new Set(Object.keys(e6)),e2=l.filter(e=>!e9.has(e.name)).map(e=>e.name);if(e2.length>0)throw Error(`failproofai: builtin policies missing an implementation: ${e2.join(", ")}`);let e8=new Set(l.map(e=>e.name)),e4=[...e9].filter(e=>!e8.has(e));if(e4.length>0)throw Error(`failproofai: policy implementations with no catalog entry: ${e4.join(", ")}`);let e5=l.map(e=>({...e,fn:e6[e.name]}));var e7=e.i(73136);let te=["claude","codex","copilot","cursor","opencode","pi","hermes","openclaw","factory","devin","antigravity","goose"],tt={apply_patch:"Edit",write_stdin:"Bash"},ti={terminal:"Bash",bash:"Bash",read_file:"Read",write_file:"Write",patch:"Edit",web_search:"WebSearch",web_extract:"WebFetch",search_files:"Grep",todo:"TodoWrite"},tn={Read:{path:"file_path"},Write:{path:"file_path"},Edit:{path:"file_path"}},to={bash:"Bash",powershell:"Bash",list_bash:"Bash",read_bash:"Bash",stop_bash:"Bash",write_bash:"Bash",list_powershell:"Bash",read_powershell:"Bash",stop_powershell:"Bash",write_powershell:"Bash",read:"Read",view:"Read",show_file:"Read",write:"Write",create:"Write",edit:"Edit",apply_patch:"Edit",str_replace_editor:"Edit",glob:"Glob",grep:"Grep",rg:"Grep",ls:"LS",web_fetch:"WebFetch"},tr={Read:{path:"file_path"},Write:{path:"file_path",file_text:"content"},Edit:{path:"file_path",old_str:"old_string",new_str:"new_string"}},ts={Shell:"Bash"},ta={bash:"Bash",read:"Read",write:"Write",edit:"Edit",apply_patch:"Edit",glob:"Glob",grep:"Grep",list:"LS",webfetch:"WebFetch",websearch:"WebSearch",todowrite:"TodoWrite",todoread:"TodoRead"},tl={Read:{filePath:"file_path"},Write:{filePath:"file_path"},Edit:{filePath:"file_path",oldString:"old_string",newString:"new_string",replaceAll:"replace_all"}},tc={bash:"Bash",read:"Read",write:"Write",edit:"Edit",glob:"Glob",grep:"Grep"},td={Read:{path:"file_path"},Write:{path:"file_path"},Edit:{path:"file_path"}},tp={exec:"Bash",read:"Read",write:"Write",edit:"Edit",grep:"Grep",glob:"Glob",web_search:"WebSearch",web_fetch:"WebFetch"},tu={Read:{path:"file_path"},Write:{path:"file_path"},Edit:{path:"file_path"}},tm={Execute:"Bash",Read:"Read",Edit:"Edit",Create:"Write",Grep:"Grep",Glob:"Glob",LS:"LS",FetchUrl:"WebFetch",WebSearch:"WebSearch",TodoWrite:"TodoWrite",Task:"Task"},tf={exec:"Bash"},th={run_command:"Bash",write_to_file:"Write",read_file:"Read",view_file:"Read",edit_file:"Edit",replace_file_content:"Edit",list_dir:"LS",find_by_name:"Glob",grep_search:"Grep",read_url_content:"WebFetch",search_web:"WebSearch"},tg={Bash:{CommandLine:"command",Cwd:"cwd"},Write:{TargetFile:"file_path",CodeContent:"content"},Edit:{TargetFile:"file_path"},Read:{TargetFile:"file_path",AbsolutePath:"file_path",File:"file_path"}},ty={shell:"Bash",write:"Write",edit:"Edit",view:"Read",read_image:"Read",glob:"Glob",grep:"Grep",tree:"LS",delegate:"Task",todo__todo_write:"TodoWrite"},tb={Read:{path:"file_path",source:"file_path"},Write:{path:"file_path"},Edit:{path:"file_path"},LS:{path:"file_path"}};["SessionStart","SessionEnd","UserPromptSubmit","PreToolUse","PermissionRequest","PermissionDenied","PostToolUse","PostToolUseFailure","Notification","SubagentStart","SubagentStop","TaskCreated","TaskCompleted","Stop","StopFailure","TeammateIdle","InstructionsLoaded","ConfigChange","CwdChanged","FileChanged","WorktreeCreate","WorktreeRemove","PreCompact","PostCompact","Elicitation","ElicitationResult","UserPromptExpansion","PostToolBatch","Setup"].filter(e=>"WorktreeCreate"!==e);var tw=e.i(81580);let tk=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;var tv=e.i(54214);function tN(e,t){let i=[];for(let o of e)if("assistant"===o.type)for(let e of o.message.content){var n;let r;if("tool_use"!==e.type)continue;let s=e.name,a=(n=t.cli,(s?"copilot"===n?to[s]??s:"cursor"===n?ts[s]??s:"codex"===n?tt[s]??s:"opencode"===n?ta[s]??s:"pi"===n?tc[s]??s:"hermes"===n?ti[s]??s:"openclaw"===n?tp[s]??s:"factory"===n?tm[s]??s:"devin"===n?tf[s]??s:"antigravity"===n?th[s]??s:"goose"===n?ty[s]??s:s:s)??s),l=function(e,t,i){let n;if(!e||!t||"object"!=typeof t||Array.isArray(t)||("copilot"===i?n=tr[e]:"opencode"===i?n=tl[e]:"pi"===i?n=td[e]:"hermes"===i?n=tn[e]:"openclaw"===i?n=tu[e]:"antigravity"===i?n=tg[e]:"goose"===i&&(n=tb[e]),!n))return t;let o={};for(let[e,i]of Object.entries(t))o[n[e]??e]=i;return o}(a,e.input,t.cli);e.result?.content&&(r=function(e){let t=Buffer.from(e,"utf-8");if(t.byteLength<=65536)return e;let i=65536;for(;i>0&&(192&t[i])==128;)i--;return t.subarray(0,i).toString("utf-8")}(e.result.content)),i.push({cli:t.cli,sessionId:t.sessionId,transcriptPath:t.transcriptPath,cwd:t.cwd,timestamp:o.timestamp,toolName:a,rawToolName:s,toolInput:l??{},toolResultText:r})}return i}async function tS(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,r=[];for(let e of function(){let e,t=(0,tw.getClaudeProjectsPath)();try{e=(0,o.readdirSync)(t,{withFileTypes:!0})}catch{return[]}return e.filter(e=>e.isDirectory()).map(e=>({name:e.name,cwd:(0,tw.decodeFolderName)(e.name),path:(0,n.join)(t,e.name)}))}()){let s;if(!t||t.has(e.cwd)){try{s=function(e){let t,i=[];try{t=(0,o.readdirSync)(e.path,{withFileTypes:!0})}catch{return i}for(let r of t)if(r.isFile()&&r.name.endsWith(".jsonl")){let t=r.name.slice(0,-6);if(!tk.test(t))continue;let s=(0,n.join)(e.path,r.name);try{let n=(0,o.statSync)(s);i.push({projectName:e.name,cwd:e.cwd,sessionId:t,transcriptPath:s,mtimeMs:n.mtimeMs,sizeBytes:n.size,isSubagent:!1})}catch{}}else if(r.isDirectory()&&tk.test(r.name)){let t,s=(0,n.join)(e.path,r.name,"subagents");if(!(0,o.existsSync)(s))continue;try{t=(0,o.readdirSync)(s,{withFileTypes:!0})}catch{continue}for(let r of t){if(!r.isFile()||!r.name.endsWith(".jsonl"))continue;let t=r.name.slice(0,-6),a=(0,n.join)(s,r.name);try{let n=(0,o.statSync)(a);i.push({projectName:e.name,cwd:e.cwd,sessionId:t,transcriptPath:a,mtimeMs:n.mtimeMs,sizeBytes:n.size,isSubagent:!0})}catch{}}}return i}(e)}catch{continue}for(let t of s)t.mtimeMs<i||r.push({cli:"claude",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.transcriptPath,mtimeMs:t.mtimeMs,sizeBytes:t.sizeBytes})}}return r}async function t$(e){let t,i;try{t=await (0,r.readFile)(e.transcriptPath,"utf-8")}catch{return[]}try{i=await (0,tv.parseLogContent)(t,"session")}catch{return[]}let n="";for(let e of t.split("\n",50))if(e.trim())try{let t=JSON.parse(e);if("string"==typeof t.cwd&&t.cwd.length>0){n=t.cwd;break}}catch{}return tN(i,{cli:"claude",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:n})}var tT=e.i(36203),tE=e.i(57232);async function tC(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,tT.getCodexProjects)())){let{cwd:r,sessions:s}=await (0,tT.getCodexSessionsByEncodedName)(e.name),a=r??"";if(!t||t.has(a))for(let t of s){let r=t.lastModified.getTime();if(r<i)continue;let s=0;try{s=(0,o.statSync)(t.path).size}catch{}t.sessionId&&n.push({cli:"codex",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:r,sizeBytes:s})}}return n}async function tA(e){let t=await (0,tE.getCodexSessionLog)(e.sessionId);return t?tN(t.entries,{cli:"codex",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tP=e.i(55851),tI=e.i(78166);async function tx(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,tP.getCopilotProjects)())){let{cwd:r,sessions:s}=await (0,tP.getCopilotSessionsByEncodedName)(e.name),a=r??"";if(!t||t.has(a))for(let t of s){let r=t.lastModified.getTime();if(r<i)continue;let s=0;try{s=(0,o.statSync)(t.path).size}catch{}t.sessionId&&n.push({cli:"copilot",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:r,sizeBytes:s})}}return n}async function tR(e){let t=await (0,tI.getCopilotSessionLog)(e.sessionId);return t?tN(t.entries,{cli:"copilot",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tO=e.i(46413),t_=e.i(72094);async function tj(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,tO.getCursorProjects)())){let{cwd:r,sessions:s}=await (0,tO.getCursorSessionsByEncodedName)(e.name),a=r??"";if(!t||t.has(a))for(let t of s){let r=t.lastModified.getTime();if(r<i)continue;let s=0;try{s=(0,o.statSync)(t.path).size}catch{}t.sessionId&&n.push({cli:"cursor",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:r,sizeBytes:s})}}return n}async function tB(e){let t=await (0,t_.getCursorSessionLog)(e.sessionId);return t?tN(t.entries,{cli:"cursor",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tD=e.i(35435),tW=e.i(99440);async function tM(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,tD.getOpenCodeProjects)())){let{cwd:o,sessions:r}=await (0,tD.getOpenCodeSessionsByEncodedName)(e.name),s=o??"";if(!t||t.has(s))for(let t of r){let o=t.lastModified.getTime();!(o<i)&&t.sessionId&&n.push({cli:"opencode",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:o,sizeBytes:0})}}return n}async function tU(e){let t=await (0,tW.getOpenCodeSessionLog)(e.sessionId);return t?tN(t.entries,{cli:"opencode",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tz=e.i(19791),tL=e.i(85116);async function tF(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,tz.getPiProjects)())){let{cwd:r,sessions:s}=await (0,tz.getPiSessionsByEncodedName)(e.name),a=r??"";if(!t||t.has(a))for(let t of s){let r=t.lastModified.getTime();if(r<i)continue;let s=0;try{s=(0,o.statSync)(t.path).size}catch{}t.sessionId&&n.push({cli:"pi",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:r,sizeBytes:s})}}return n}async function tq(e){let t=await (0,tL.getPiSessionLog)(e.sessionId);return t?tN(t.entries,{cli:"pi",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tH=e.i(64828),tJ=e.i(28898),tG=e.i(3605);async function tZ(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=await (0,tH.getHermesSessions)(),o=[];for(let e of n)!(e.mtimeMs<i)&&(!(e.messageCount<=0)||e.hasMessages)&&(!t||e.cwd&&t.has(e.cwd))&&o.push({cli:"hermes",projectName:e.cwd?(0,tw.encodeFolderName)(e.cwd):e.source?(0,tJ.hermesProjectPath)(e.profile,e.source):`hermes:${e.profile}`,sessionId:e.sessionId,transcriptPath:`hermes://${e.sessionId}`,mtimeMs:e.mtimeMs,sizeBytes:e.messageCount});return o}async function tY(e){let t=await (0,tG.getHermesSessionLog)(e.sessionId);return t?tN(t.entries,{cli:"hermes",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tK=e.i(90624),tQ=e.i(64199);async function tV(e={}){if(e.projects&&e.projects.length>0)return[];let t=e.sinceMs??0,i=[];for(let e of(await (0,tK.getOpenClawSessions)()))e.mtimeMs<t||i.push({cli:"openclaw",projectName:(0,tK.openClawProjectPath)(e.agentId,e.channel),sessionId:e.sessionId,transcriptPath:e.transcriptPath,mtimeMs:e.mtimeMs,sizeBytes:e.sizeBytes});return i}async function tX(e){let t=await (0,tQ.getOpenClawSessionLog)(e.sessionId);return t?tN(t.entries,{cli:"openclaw",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var t0=e.i(28246);async function t1(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(0,t0.listFactoryTranscripts)())!(e.mtimeMs<i)&&(!t||t.has(e.cwd))&&n.push({cli:"factory",projectName:e.projectName,sessionId:e.sessionId,transcriptPath:e.transcriptPath,mtimeMs:e.mtimeMs,sizeBytes:e.sizeBytes});return n}async function t3(e){let t;try{t=await (0,r.readFile)(e.transcriptPath,"utf-8")}catch{return[]}let i=(0,tv.parseRawLines)(t,"session"),n=(0,t0.factoryLinesToLogEntries)(i,"session"),o="";for(let e of i)if(e&&"object"==typeof e&&"session_start"===e.type){let t=e.cwd;if("string"==typeof t&&t.length>0){o=t;break}}return tN(n,{cli:"factory",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:o})}var t6=e.i(93114),t9=e.i(30441);async function t2(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[],o=await (0,t9.getAntigravityIndex)();for(let e of(0,t6.listAntigravityTranscripts)()){if(e.mtimeMs<i)continue;let r=o.get(e.conversationId)?.cwd;(!t||r&&t.has(r))&&n.push({cli:"antigravity",projectName:r?(0,tw.encodeFolderName)(r):"antigravity",sessionId:e.conversationId,transcriptPath:e.transcriptPath,mtimeMs:e.mtimeMs,sizeBytes:e.sizeBytes})}return n}async function t8(e){let t;try{t=await (0,r.readFile)(e.transcriptPath,"utf-8")}catch{return[]}let i=(0,tv.parseRawLines)(t,"session"),n=(0,t6.antigravityLinesToLogEntries)(i,"session"),o="";for(let e of i){if(!e||"object"!=typeof e)continue;let t=e.tool_calls;if(Array.isArray(t)){for(let e of t){let t=e&&"object"==typeof e?e.args:void 0,i=t&&"object"==typeof t?t.Cwd:void 0;if("string"==typeof i&&i.length>0){o=i;break}}if(o)break}}return tN(n,{cli:"antigravity",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:o})}var t4=e.i(79364),t5=e.i(40375);async function t7(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=await (0,t4.getDevinSessions)(),o=[];for(let e of n)!(e.mtimeMs<i)&&(!t||e.cwd&&t.has(e.cwd))&&o.push({cli:"devin",projectName:e.projectName,sessionId:e.sessionId,transcriptPath:`devin-db://${e.sessionId}`,mtimeMs:e.mtimeMs,sizeBytes:0});return o}async function ie(e){let t=await (0,t5.getDevinSessionLog)(e.sessionId);return t?tN(t.entries,{cli:"devin",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var it=e.i(69164),ii=e.i(36618);let io={claude:{cli:"claude",listTranscripts:tS,streamEvents:t$},codex:{cli:"codex",listTranscripts:tC,streamEvents:tA},copilot:{cli:"copilot",listTranscripts:tx,streamEvents:tR},cursor:{cli:"cursor",listTranscripts:tj,streamEvents:tB},opencode:{cli:"opencode",listTranscripts:tM,streamEvents:tU},pi:{cli:"pi",listTranscripts:tF,streamEvents:tq},hermes:{cli:"hermes",listTranscripts:tZ,streamEvents:tY},openclaw:{cli:"openclaw",listTranscripts:tV,streamEvents:tX},factory:{cli:"factory",listTranscripts:t1,streamEvents:t3},devin:{cli:"devin",listTranscripts:t7,streamEvents:ie},antigravity:{cli:"antigravity",listTranscripts:t2,streamEvents:t8},goose:{cli:"goose",listTranscripts:async function(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=await (0,it.getGooseSessions)(),o=[];for(let e of n)!(e.mtimeMs<i)&&(!t||e.cwd&&t.has(e.cwd))&&o.push({cli:"goose",projectName:e.projectName,sessionId:e.sessionId,transcriptPath:`goose-db://${e.sessionId}`,mtimeMs:e.mtimeMs,sizeBytes:0});return o},streamEvents:async function(e){let t=await (0,ii.getGooseSessionLog)(e.sessionId);return t?tN(t.entries,{cli:"goose",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}}},ir=/\.(?:ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|kt|swift|rb|php|c|h|cc|cpp|hpp|cs|scala|sh|bash|zsh|json|yaml|yml|toml|md|txt|sql|html|css|scss|sass)$/i,is=["/","/home","/usr","/etc","/var","/opt","/Users"],ia="rereadAfterEdit",il=[{name:"redundant-cd-cwd",description:"Bash commands prefixed with `cd <cwd> && …` even though commands already run in cwd.",category:"Wasteful",severity:"info",displayTitle:"Prepended cd <cwd> before commands",impact:"Pure waste — your agent's shell already runs in `cwd`.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;if("string"!=typeof t||!e.cwd)return null;let i=t.trimStart(),n=/^cd\s+(?:"([^"]+)"|'([^']+)'|(\S+))\s*&&\s*([\s\S]+)$/.exec(i);if(!n)return null;let o=(n[1]??n[2]??n[3]??"").replace(/\/+$/,"");if(o!==e.cwd.replace(/\/+$/,""))return null;let r=n[4].trim();return{example:`cd ${o} && ${r}`}}},{name:"prefer-edit-over-read-cat",description:"Bash `cat`/`head`/`tail`/`less`/`more` on a single source file — use Read.",category:"Wasteful",severity:"info",displayTitle:"Used `cat`/`head`/`tail` on a source file",impact:"Burns tokens; the Read tool returns content directly without going through Bash output.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;if("string"!=typeof t)return null;let i=t.trim();if(/[|<>;&`$()]/.test(i))return null;let n=/^(cat|head|tail|less|more)\s+(?:-\S+\s+)*(?:"([^"]+)"|'([^']+)'|(\S+))\s*$/.exec(i);if(!n)return null;let o=n[2]??n[3]??n[4]??"";return!o||/(?:^|\/)\.env(?:\..+)?$/.test(o)||!ir.test(o)?null:{example:i}}},{name:"prefer-edit-over-sed-awk",description:"Bash `sed -i`/`awk` in-place edits — use Edit.",category:"Wasteful",severity:"info",displayTitle:"Used sed -i or awk for an in-place edit",impact:"Edit tool is safer and produces a diff the agent can verify.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;if("string"!=typeof t)return null;let i=t.trim();return/(?:^|\s|;|&&|\|\|)sed\b[^|]*\s-i(?=\b|['"])/.test(i)||/(?:^|\s|;|&&|\|\|)awk\b[^|]*\s>\s*\S+/.test(i)&&!/\|/.test(i)?{example:i}:null}},{name:"prefer-write-over-heredoc",description:"Bash heredoc / `echo > file` writing multi-line content — use Write.",category:"Wasteful",severity:"info",displayTitle:"Used heredoc / `echo > file` to write a multi-line file",impact:"Write tool handles escaping and is verifiable.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;return"string"!=typeof t?null:/<<-?\s*['"]?[A-Za-z_][A-Za-z0-9_]*['"]?\s*>\s*\S/.test(t)||/(?:^|\s|;|&&|\|\|)(?:echo|printf)\s+["'][^"']*\n[^"']*["']\s*>\s*\S/.test(t)?{example:t.replace(/\s+/g," ").trim().slice(0,160)}:null}},{name:"sleep-polling-loop",description:"Bash long `sleep` or while-sleep polling loops.",category:"Wasteful",severity:"info",displayTitle:"Used a long sleep or while-sleep polling loop",impact:"Burns wall-clock; better to wait for an explicit signal.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;if("string"!=typeof t)return null;if(/\bwhile\b[\s\S]*?\bsleep\b[\s\S]*?\bdone\b/.test(t))return{example:t.replace(/\s+/g," ").trim().slice(0,160)};let i=/\bsleep\s+(\d+(?:\.\d+)?)(m|h|d)?\b/.exec(t);if(i){let e=parseFloat(i[1]),n=i[2]??"s";if(("m"===n?60*e:"h"===n?3600*e:"d"===n?86400*e:e)>=30)return{example:t.replace(/\s+/g," ").trim().slice(0,160)}}return null}},{name:"find-from-root",description:"Bash `find` against `/`, `/home`, `/usr`, etc. — scope to cwd instead.",category:"Risky",severity:"warn",displayTitle:"Ran find from /, /home, /usr, etc.",impact:"Filesystem-wide finds exhaust resources and rarely return useful results.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;if("string"!=typeof t)return null;let i=t.trim(),n=/(?:^|[\s;|&])find\s+(?:-\S+\s+)*("[^"]+"|'[^']+'|\S+)/.exec(i);if(!n)return null;let o=n[1].replace(/^["']|["']$/g,"").replace(/\/+$/,"")||"/";return is.includes(o)?{example:i.slice(0,160)}:null}},{name:"git-commit-no-verify",description:"git commit invoked with --no-verify / -n, skipping hooks.",category:"Risky",severity:"warn",displayTitle:"Committed with --no-verify",impact:"Skips pre-commit hooks that exist to catch broken or unsafe code.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;return"string"!=typeof t?null:/\bgit\s+commit\b/.test(t)&&(/\s--no-verify\b/.test(t)||/\s-n\b/.test(t))?{example:t.replace(/\s+/g," ").trim().slice(0,160)}:null}},{name:"reread-after-edit",description:"Read of a file that was just Edit'd or Write'n in the same session.",category:"Wasteful",severity:"info",displayTitle:"Re-read a file it just edited",impact:"Edit/Write already returned the updated content; the second Read is wasted tokens.",detect(e,t){let i,n=((i=t[ia])||(i={countdown:new Map},t[ia]=i),i),o=e.toolInput.file_path,r="string"==typeof o?o:null;for(let[e,t]of n.countdown)t<=1?n.countdown.delete(e):n.countdown.set(e,t-1);return r?"Edit"===e.toolName||"Write"===e.toolName?(n.countdown.set(r,5),null):"Read"===e.toolName&&n.countdown.has(r)?(n.countdown.delete(r),{example:`Read ${r} immediately after Edit/Write`}):null:null}}],ic=["cowboy","explorer","ghost","optimist","hammer","architect"],id={explorer:.38,architect:.33,hammer:.11,cowboy:.11,optimist:.07,ghost:.01,precision:0,goldfish:0},ip={optimist:0,cowboy:0,explorer:0,goldfish:0,architect:0,precision:0,hammer:0,ghost:0};for(let e of ic)ip[e]=Math.max(id[e],.05);var iu=e.i(66680),im=e.i(79857);let ih=[1],ig=/^[a-f0-9]{64}$/,iy=/^[A-Za-z0-9._-]{1,64}\/[A-Za-z0-9._-]{1,64}$/,ib=/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/,iw=/^[A-Za-z0-9._-]{1,128}$/;function ik(e){return e instanceof Error?e.message:String(e)}let iv=null,iN=null;function iS(){if(iv)return iv;let e=e5.map(e=>`${e.name}|${e.fn.toString()}`).sort().join("\n"),t="";try{t=(function(){let e,t=process.env.FAILPROOFAI_PACK_DIR?(0,n.resolve)(process.env.FAILPROOFAI_PACK_DIR,"installed.json"):(0,im.packsInstalledFile)();if(!(0,o.existsSync)(t))return{packs:[],errors:[]};try{e=JSON.parse((0,o.readFileSync)(t,"utf8"))}catch(e){return{packs:[],errors:[{id:null,reason:`unreadable pack manifest: ${ik(e)}`}]}}if(!e||"object"!=typeof e)return{packs:[],errors:[{id:null,reason:"pack manifest is not an object"}]};let i=e;if(!ih.includes(i.schemaVersion))return{packs:[],errors:[{id:null,reason:`unsupported pack manifest schema ${String(i.schemaVersion)} (supported: ${ih.join(", ")})`}]};if(!Array.isArray(i.packs))return{packs:[],errors:[{id:null,reason:"pack manifest packs is not an array"}]};let r=process.env.FAILPROOFAI_PACK_DIR??(0,im.packsDir)(),s=[],a=[],l=new Set;for(let e of i.packs){let t=e&&"object"==typeof e&&"string"==typeof e.id?e.id:null;try{let t=function(e,t){if(!t||"object"!=typeof t)throw Error("pack entry is not an object");let i=function(e){if("string"!=typeof e.id||!iy.test(e.id))throw Error(`unsafe pack id ${JSON.stringify(e.id)}`);if("string"!=typeof e.version||!ib.test(e.version))throw Error(`invalid version for pack ${e.id}`);if(void 0!==e.effect&&"enforce"!==e.effect&&"observe"!==e.effect)throw Error(`unknown effect ${JSON.stringify(e.effect)} for pack ${e.id}`);return{id:e.id,version:e.version,effect:e.effect??"enforce"}}(t);if("string"!=typeof t.source||0===t.source.length)throw Error(`pack ${t.id} has no source`);if("string"!=typeof t.sha256||!ig.test(t.sha256))throw Error(`invalid SHA-256 for pack ${t.id}`);let r=i.effect,s=function(e,t){if(!t||(0,n.isAbsolute)(t))throw Error(`unsafe managed policy path ${JSON.stringify(t)}`);let i=(0,n.resolve)(e,t),r=(0,n.relative)(e,i);if(r.startsWith("..")||(0,n.isAbsolute)(r))throw Error(`managed policy path escapes its root: ${JSON.stringify(t)}`);let s=(0,o.realpathSync)(e),a=(0,o.realpathSync)(i),l=(0,n.relative)(s,a);if(l.startsWith("..")||(0,n.isAbsolute)(l))throw Error(`managed policy symlink escapes its root: ${JSON.stringify(t)}`);return a}(e,t.entry),a=(0,iu.createHash)("sha256").update((0,o.readFileSync)(s)).digest("hex");if(a!==t.sha256)throw Error(`pack ${t.id} failed integrity verification: expected ${t.sha256}, got ${a}`);if(!Array.isArray(t.policies))throw Error(`pack ${t.id} policies is not an array`);let l=t.policies.map((e,i)=>(function(e,t,i){let n=`${e} policy #${i}`;if(!t||"object"!=typeof t)throw Error(`${n} is not an object`);let o=t.name;if("string"!=typeof o||!iw.test(o))throw Error(`${n} has an unsafe name ${JSON.stringify(o)}`);if("alwaysOn"in t)throw Error(`${n} declares alwaysOn, which packs may not set`);if("string"!=typeof t.description||0===t.description.length)throw Error(`${n} is missing a description`);if("string"!=typeof t.category||0===t.category.length)throw Error(`${n} is missing a category`);if("boolean"!=typeof t.defaultEnabled)throw Error(`${n} is missing defaultEnabled`);if(!t.match||"object"!=typeof t.match)throw Error(`${n} is missing a match`);return t})(t.id,e,i)),c=new Set;for(let e of l){if(c.has(e.name))throw Error(`pack ${t.id} declares ${e.name} twice`);c.add(e.name)}let d=null;if(void 0!==t.enabled){if(!Array.isArray(t.enabled)||t.enabled.some(e=>"string"!=typeof e))throw Error(`pack ${t.id} enabled is not an array of names`);d=t.enabled.filter(e=>c.has(e))}return{id:i.id,version:i.version,source:t.source,path:s,sha256:t.sha256,effect:r,policies:l,enabled:d}}(r,e);if(l.has(t.id))throw Error(`duplicate pack id ${t.id}`);l.add(t.id),s.push(t)}catch(n){let i=e&&("observe"===e.effect||"enforce"===e.effect)?e.effect:"enforce";a.push({id:t,reason:ik(n),effect:i,...Array.isArray(e?.policies)?{declared:function(e){let t=[];for(let i of e)i&&"object"==typeof i&&"string"==typeof i.name&&i.match&&"object"==typeof i.match&&t.push(i);return t}(e.policies)}:{}})}}return{packs:s,errors:a}})().packs.map(e=>`${e.id}|${e.version}|${e.sha256}`).sort().join("\n")}catch{t=""}let i=t?`${e}
2
- ${t}`:e;return iv=(0,iu.createHash)("sha1").update(i).digest("hex").slice(0,16)}function i$(){if(iN)return iN;let e=il.map(e=>`${e.name}|${e.detect.toString()}`).sort().join("\n");return iN=(0,iu.createHash)("sha1").update(e).digest("hex").slice(0,16)}function iT(e){let t=(0,im.auditCacheDir)(),i=(0,iu.createHash)("sha1").update(e).digest("hex");return(0,n.join)(t,`${i}.json`)}var iE=e.i(49335),iC=e.i(10659);function iA(e,t){let i=e.trim(),n="string"==typeof t?t.trim():"";return n?i?`${i}. ${n}`:n:i}function iP(e,t){if(!e?.policyParams)return;let i=e.policyParams[t];if(i)return i;let n=`${f}/`;if(t.startsWith(n))return e.policyParams[t.slice(n.length)]}async function iI(e,t,i,n){let o=t.tool_name,r=t.tool_input,s=function(e,t){let i=globalThis[m];i||g(i=new Map);let n=`${e}:${t??""}`,o=i.get(n);if(o)return o;let r=y().filter(i=>(!i.match.events||!(i.match.events.length>0)||!!i.match.events.includes(e))&&(!i.match.toolNames||!(i.match.toolNames.length>0)||!!t&&!!i.match.toolNames.includes(t))).sort((e,t)=>t.priority-e.priority);return i.set(n,r),r}(e,o);if((0,w.hookLogInfo)(`evaluating ${s.length} policies for ${e}`),0===s.length)return{exitCode:0,stdout:"",stderr:"",policyName:null,reason:null,decision:"allow"};let a={eventType:e,payload:t,toolName:o,toolInput:r,session:i,cli:i?.cli},l=[],c=[];for(let t of s){let o,r,s=t.params,d=iP(n,t.name)??{};if(s){let e={};for(let[t,i]of Object.entries(s))e[t]=t in d?d[t]:i.default;o={...a,params:e}}else o={...a,params:d};try{r=await t.fn(o)}catch(o){let n=o instanceof Error?o.message:String(o);(0,w.hookLogWarn)(`policy "${t.name}" threw: ${n}`),t.name.startsWith(`${f}/`)&&(0,iE.trackHookEvent)((0,iC.getInstanceId)(),"policy_evaluation_error",{policy_name:t.name,event_type:e,cli:i?.cli??null,error_type:o instanceof Error?o.name:"unknown"});continue}if("deny"===r.decision){let s,a=iA(r.reason??`Blocked by policy: ${t.name}`,iP(n,t.name)?.hint);(0,w.hookLogInfo)(`deny by "${t.name}": ${a}`),s=o.toolName?o.toolName:"UserPromptSubmit"===e?"prompt":"SessionStart"===e?"session start":"SessionEnd"===e?"session end":"Stop"===e?"stop":"operation";let l=`Blocked ${s} by failproofai because: ${a}, as per the policy configured by the user`;if(i?.cli==="cursor"){if("Stop"===e||"SubagentStop"===e)return{exitCode:0,stdout:JSON.stringify({followup_message:`MANDATORY ACTION REQUIRED from failproofai (policy: ${t.name}): ${a}
1
+ module.exports=[97610,e=>{"use strict";var t=e.i(89171),i=e.i(71809),n=e.i(50227),o=e.i(2157),s=e.i(12714),r=e.i(74533),a=e.i(60526);let l=[{name:"sanitize-jwt",description:"Stop Claude from reading JWTs in tool responses",displayTitle:"Redacted JWT tokens from tool output",impact:"Stops the agent from echoing auth tokens it saw in command output.",match:{events:["PostToolUse"]},defaultEnabled:!0,category:"Sanitize"},{name:"sanitize-api-keys",description:"Stop Claude from reading API keys (OpenAI, Anthropic, GitHub, AWS, Stripe, Google) in tool responses",displayTitle:"Redacted API keys from tool output",impact:"Catches OpenAI / Anthropic / GitHub / AWS / Stripe / Google keys before the model sees them.",match:{events:["PostToolUse"]},defaultEnabled:!0,category:"Sanitize",params:{additionalPatterns:{type:"pattern[]",description:"Additional API key patterns to scrub, each with { regex, label }",default:[]}}},{name:"sanitize-connection-strings",description:"Stop Claude from reading database connection strings with embedded credentials in tool responses",displayTitle:"Redacted database connection strings from tool output",impact:"Strips embedded DB credentials before they reach the model context.",match:{events:["PostToolUse"]},defaultEnabled:!0,category:"Sanitize"},{name:"sanitize-private-key-content",description:"Stop Claude from reading PEM private key content in tool responses",displayTitle:"Redacted PEM private keys from tool output",impact:"Prevents private key bodies from being echoed into chat context.",match:{events:["PostToolUse"]},defaultEnabled:!0,category:"Sanitize"},{name:"sanitize-bearer-tokens",displayTitle:"Redacted bearer tokens from tool output",impact:"Strips Authorization: Bearer values before they hit the model.",description:"Stop Claude from reading Authorization Bearer tokens in tool responses",match:{events:["PostToolUse"]},defaultEnabled:!0,category:"Sanitize"},{name:"protect-env-vars",displayTitle:"Tried to dump environment variables to chat",impact:"Env vars often contain secrets; blocking `env` / `printenv` keeps them out of the model context.",description:"Prevent commands that read environment variables",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!0,category:"Environment"},{name:"block-env-files",displayTitle:"Tried to read or write a .env file",impact:"`.env` files routinely contain API keys and DB credentials.",description:"Block reading/writing .env files",match:{events:["PreToolUse"]},defaultEnabled:!0,category:"Environment"},{name:"block-read-outside-cwd",displayTitle:"Tried to read files outside your project directory",impact:"Stops the agent from peeking at neighboring repos or your home directory.",description:"Block file reads outside the session working directory",match:{events:["PreToolUse"],toolNames:["Read","Glob","Grep","Bash"]},defaultEnabled:!1,category:"Environment",params:{allowPaths:{type:"string[]",description:"Absolute paths outside cwd that are allowed to be read",default:[]}}},{name:"block-sudo",displayTitle:"Tried to run a command with sudo",impact:"Sudo gives the agent root — blocked unless explicitly allow-listed.",description:"Block sudo commands",match:{events:["PreToolUse","PermissionRequest"],toolNames:["Bash"]},defaultEnabled:!0,category:"Dangerous Commands",params:{allowPatterns:{type:"string[]",description:"Sudo command patterns to allow, matched token-by-token (e.g. 'sudo systemctl status')",default:[]}}},{name:"block-curl-pipe-sh",displayTitle:"Tried to pipe a downloaded script straight to a shell",impact:"`curl ... | sh` runs unverified remote code on your machine.",description:"Block piping downloads to shell",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!0,category:"Dangerous Commands"},{name:"block-rm-rf",displayTitle:"Tried to recursively delete a system path",impact:"Catches catastrophic `rm -rf /` and Windows equivalents.",description:"Prevent catastrophic deletions",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Dangerous Commands",params:{allowPaths:{type:"string[]",description:"Paths that are allowed to be recursively deleted",default:[]}}},{name:"block-failproofai-commands",displayTitle:"Tried to disable, pause or modify failproofai itself",impact:"An agent that can pause or remove enforcement can switch off every other policy.",description:"Block failproofai CLI commands, self-pause and uninstallation",match:{events:["PreToolUse","PermissionRequest"],toolNames:["Bash"]},defaultEnabled:!0,alwaysOn:!0,category:"Dangerous Commands"},{name:"block-kubectl",displayTitle:"Tried to run a Kubernetes command",impact:"kubectl can change live cluster state — gated unless allow-listed.",description:"Block kubectl commands (Kubernetes cluster mutations)",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"kubectl command patterns to allow, matched token-by-token (e.g. 'kubectl get *', 'kubectl describe *')",default:[]}}},{name:"block-terraform",displayTitle:"Tried to run a Terraform/OpenTofu command",impact:"Terraform mutates real infrastructure — gated unless allow-listed.",description:"Block terraform and tofu (OpenTofu) commands",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"terraform/tofu command patterns to allow (e.g. 'terraform plan', 'terraform validate')",default:[]}}},{name:"block-aws-cli",displayTitle:"Tried to run an AWS CLI command",impact:"AWS CLI can spend money or break prod — gated.",description:"Block aws CLI commands",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"aws CLI command patterns to allow (e.g. 'aws s3 ls *', 'aws sts get-caller-identity')",default:[]}}},{name:"block-gcloud",displayTitle:"Tried to run a Google Cloud command",impact:"gcloud can spend money or break prod — gated.",description:"Block gcloud (Google Cloud) CLI commands",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"gcloud command patterns to allow (e.g. 'gcloud auth list', 'gcloud config list')",default:[]}}},{name:"block-az-cli",displayTitle:"Tried to run an Azure CLI command",impact:"az can spend money or break prod — gated.",description:"Block az (Azure) CLI commands",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"az CLI command patterns to allow (e.g. 'az account show', 'az group list')",default:[]}}},{name:"block-helm",displayTitle:"Tried to run a Helm command",impact:"Helm releases mutate cluster state — gated.",description:"Block helm commands",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"helm command patterns to allow (e.g. 'helm list', 'helm status *')",default:[]}}},{name:"block-gh-pipeline",displayTitle:"Tried to run a privileged GitHub CLI pipeline command",impact:"Catches `gh workflow run`, `gh pr merge`, `gh secret set`, etc.",description:"Block gh CLI pipeline-trigger subcommands (workflow run, run rerun/cancel, pr merge, release create/delete, cache delete, secret set/delete)",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Infra Commands",params:{allowPatterns:{type:"string[]",description:"gh pipeline command patterns to allow (e.g. specific scripted invocations); read-only gh subcommands like 'gh pr view' and 'gh run list' are not matched by this policy",default:[]}}},{name:"block-secrets-write",displayTitle:"Tried to write a secret-key file",impact:"Stops the agent from creating `.pem`, `id_rsa`, `credentials.json`, etc.",description:"Block writing secret key files",match:{events:["PreToolUse"],toolNames:["Write"]},defaultEnabled:!1,category:"Dangerous Commands",params:{additionalPatterns:{type:"string[]",description:"Additional filename patterns (substrings) to block",default:[]}}},{name:"block-push-master",displayTitle:"Tried to push directly to main/master",impact:"Direct pushes to a protected branch bypass review.",description:"Block pushing to main/master",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!0,category:"Git",params:{protectedBranches:{type:"string[]",description:"Branch names to protect from direct pushes",default:["main","master"]}}},{name:"block-force-push",displayTitle:"Tried to force-push",impact:"Force-pushes rewrite history and can clobber teammates' work.",description:"Prevent force-pushing to any branch",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Git"},{name:"block-work-on-main",displayTitle:"Tried to commit or merge on main/master",impact:"Work should land via PR — direct commits skip review.",description:"Block git commits and merges on main/master branch",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Git",params:{protectedBranches:{type:"string[]",description:"Branch names where commits/merges are blocked",default:["main","master"]}}},{name:"warn-git-amend",displayTitle:"Used git commit --amend",impact:"Amending after a push rewrites history that others may have pulled.",description:"Warns before amending git commits, which rewrites history",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Git"},{name:"warn-git-stash-drop",displayTitle:"Tried to drop or clear git stash",impact:"Stash deletions are permanent and silent.",description:"Warns before permanently deleting stashed changes",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Git"},{name:"warn-all-files-staged",displayTitle:"Staged all files with git add -A / .",impact:"Wide stages routinely catch generated files or secrets you didn't intend to commit.",description:"Warns before staging all working tree files with git add -A / . / --all",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Git"},{name:"warn-destructive-sql",displayTitle:"Ran destructive SQL (DROP / TRUNCATE / DELETE without WHERE)",impact:"Easy way to wipe a table by accident.",description:"Warn before executing destructive SQL (DROP/TRUNCATE/DELETE without WHERE) via database clients",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Database"},{name:"warn-schema-alteration",displayTitle:"Altered a database schema column",impact:"ALTER TABLE operations can lock tables and break readers.",description:"Warns before SQL schema changes (ALTER TABLE with column or rename operations)",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Database"},{name:"warn-package-publish",displayTitle:"Tried to publish a package",impact:"Publishes are irreversible — `npm publish` / `cargo publish` shouldn't happen without intent.",description:"Warn before publishing packages to public registries (npm, PyPI, crates.io, RubyGems, etc.)",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Packages & System"},{name:"warn-global-package-install",displayTitle:"Installed a package globally",impact:"`npm i -g`, `cargo install`, `pip --user` pollute your machine outside the project.",description:"Warns before installing packages globally (npm -g, cargo install, etc.)",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Packages & System"},{name:"prefer-package-manager",displayTitle:"Used a non-preferred package manager",impact:"Mixing package managers creates lockfile churn for your team.",description:"Blocks non-preferred package managers and tells Claude to use an allowed one (e.g., uv instead of pip)",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Packages & System",params:{allowed:{type:"string[]",description:"Allowed package manager names (e.g. ['uv', 'bun']). Any detected manager not in this list is blocked.",default:[]},blocked:{type:"string[]",description:"Additional manager names to block beyond the built-in list (e.g. ['pdm', 'pipx']).",default:[]}}},{name:"warn-large-file-write",displayTitle:"Wrote a file larger than the configured threshold",impact:"Catches accidentally large file writes (logs, binaries, model dumps).",description:"Warn before writing files larger than 1MB (configurable via thresholdKb param)",match:{events:["PreToolUse"],toolNames:["Write"]},defaultEnabled:!1,category:"Packages & System",params:{thresholdKb:{type:"number",description:"File size threshold in KB above which a warning is issued",default:1024}}},{name:"warn-background-process",displayTitle:"Started a long-lived background process",impact:"Catches `nohup` / `&` / `screen` / `tmux` / `disown` patterns that the agent often forgets to clean up.",description:"Warns before starting detached or background processes",match:{events:["PreToolUse"],toolNames:["Bash"]},defaultEnabled:!1,category:"Packages & System"},{name:"warn-repeated-tool-calls",displayTitle:"Called the same tool 3+ times with identical arguments",impact:"Usually a sign of a stuck loop burning tokens.",description:"Warn when the same tool is called 3+ times with identical parameters",match:{events:["PreToolUse"]},defaultEnabled:!1,category:"AI Behavior"},{name:"require-commit-before-stop",displayTitle:"Stopped with uncommitted changes",impact:"Work not in a commit is invisible to teammates and easy to lose.",description:"Require all changes to be committed before Claude stops",match:{events:["Stop"]},defaultEnabled:!1,category:"Workflow"},{name:"require-push-before-stop",displayTitle:"Stopped with unpushed commits",impact:"Local-only commits won't trigger CI or be reviewable.",description:"Require all commits to be pushed to remote before Claude stops",match:{events:["Stop"]},defaultEnabled:!1,category:"Workflow",params:{remote:{type:"string",description:"Remote name to push to (default: origin)",default:"origin"},baseBranch:{type:"string",description:"Base branch to compare against (default: main)",default:"main"}}},{name:"require-pr-before-stop",displayTitle:"Stopped without a PR for the branch",impact:"Branches without PRs don't get reviewed.",description:"Require a pull request to exist for the current branch before Claude stops",match:{events:["Stop"]},defaultEnabled:!1,category:"Workflow",params:{baseBranch:{type:"string",description:"Base branch to compare against (default: main)",default:"main"}}},{name:"require-no-conflicts-before-stop",displayTitle:"Stopped with a branch that conflicts with main",impact:"Conflicting branches can't merge — surface them early.",description:"Require the current branch to merge cleanly with the base branch before Claude stops",match:{events:["Stop"]},defaultEnabled:!1,category:"Workflow",params:{baseBranch:{type:"string",description:"Base branch to check for conflicts against (default: main)",default:"main"}}},{name:"require-ci-green-before-stop",displayTitle:"Stopped with failing CI",impact:"Failing CI blocks deploy.",description:"Require CI checks to pass on the current HEAD commit before Claude stops (ignores stale runs on prior commits)",match:{events:["Stop"]},defaultEnabled:!1,category:"Workflow"}];function c(e){return e?{decision:"allow",reason:e}:{decision:"allow"}}function d(e){return{decision:"deny",reason:e}}function p(e){return{decision:"instruct",reason:e}}let u="__FAILPROOFAI_POLICY_REGISTRY__",m="__FAILPROOFAI_POLICY_INDEX_CACHE__",f="failproofai";function h(e){return e.includes("/")?e:`${f}/${e}`}function g(e){globalThis[m]=e}function y(){let e=globalThis;return e[u]||(e[u]=[]),e[u]}var b=e.i(79857);let w={info:0,warn:1,error:2},k=(0,b.logsDir)(),v=!1,N="warn",S=!1,T=k;function $(e){return!function(){if(v)return;v=!0;let e=(process.env.FAILPROOFAI_LOG_LEVEL??"").toLowerCase();("info"===e||"warn"===e||"error"===e)&&(N=e);let t=(process.env.FAILPROOFAI_HOOK_LOG_FILE??"").trim();t&&(S=!0,"1"!==t&&"true"!==t&&(T=t))}(),w[e]>=w[N]}function P(e,t){process.stderr.write(`[failproofai:hook] ${e} ${t}
2
+ `)}function E(e,t){if(S)try{(0,o.existsSync)(T)||(0,o.mkdirSync)(T,{recursive:!0});let i=(0,n.join)(T,"hooks.log");try{if((0,o.statSync)(i).size>=524288){let e=`hooks-${Date.now()}.log`;(0,o.renameSync)(i,(0,n.join)(T,e))}}catch{}let s=new Date().toISOString(),r=`[${s}] ${e} ${t}
3
+ `;(0,o.appendFileSync)(i,r,"utf-8")}catch{}}function C(e){$("info")&&(P("INFO",e),E("INFO",e))}function I(e){$("warn")&&(P("WARN",e),E("WARN",e))}let A=function(e){let t=e.replaceAll("\\","/");for(let e of[".claude",".codex",".copilot",".cursor",".opencode",".pi",".gemini"]){let i=(0,n.join)((0,a.homedir)(),e).replaceAll("\\","/");if(t===i||t.startsWith(i+"/"))return!0}for(let e of[(0,n.join)(".config","opencode"),(0,n.join)(".local","share","opencode")]){let i=(0,n.join)((0,a.homedir)(),e).replaceAll("\\","/");if(t===i||t.startsWith(i+"/"))return!0}return!1},x=function(e){return!!(/[\\/]\.claude[\\/]settings(?:\.[^/\\]+)?\.json$/.test(e)||/[\\/]\.codex[\\/]hooks\.json$/.test(e)||/[\\/]\.copilot[\\/]hooks[\\/][^/\\]+\.json$/.test(e)||/[\\/]\.github[\\/]hooks[\\/][^/\\]+\.json$/.test(e)||/[\\/]\.cursor[\\/]hooks\.json$/.test(e)||/[\\/]\.opencode[\\/]opencode\.jsonc?$/.test(e)||/[\\/]\.opencode[\\/]plugins[\\/][^/\\]+\.(?:mjs|js|ts)$/.test(e)||/[\\/]\.config[\\/]opencode[\\/]opencode\.jsonc?$/.test(e)||/[\\/]\.config[\\/]opencode[\\/]config\.json$/.test(e)||/[\\/]\.config[\\/]opencode[\\/]plugins[\\/][^/\\]+\.(?:mjs|js|ts)$/.test(e)||/[\\/]\.pi[\\/](?:agent[\\/])?settings\.json$/.test(e)||/[\\/]\.pi[\\/](?:agent[\\/])?extensions[\\/]/.test(e)||/[\\/]\.gemini[\\/]settings\.json$/.test(e)||/[\\/]\.gemini[\\/]config[\\/]hooks\.json$/.test(e))};function R(e){return e.toolInput?.command??""}function O(e){return e.toolInput?.file_path??""}function _(e){return e.trim().split(/\s+/).map(e=>e.replace(/^['"]|['"]$/g,""))}let j=new Set(["&&","||","|",";"]),B=/[;&<>`$()\\]/,D=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/,W=[[/sk-ant-[A-Za-z0-9\-_]{20,}/,"Anthropic API key"],[/sk-proj-[A-Za-z0-9\-_]{20,}/,"OpenAI project API key"],[/sk-[A-Za-z0-9]{20,}/,"OpenAI API key"],[/ghp_[A-Za-z0-9]{36}/,"GitHub personal access token"],[/github_pat_[A-Za-z0-9_]{82}/,"GitHub fine-grained token"],[/AKIA[A-Z0-9]{16}/,"AWS access key ID"],[/sk_live_[A-Za-z0-9]{24,}/,"Stripe live secret key"],[/sk_test_[A-Za-z0-9]{24,}/,"Stripe test secret key"],[/AIza[0-9A-Za-z\-_]{35}/,"Google API key"]],M=/(?:postgresql|postgres|mysql|mongodb(?:\+srv)?|redis|amqps?|smtps?):\/\/[^@\s]+@/,U=/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----/,z=/Authorization:\s*Bearer\s+[A-Za-z0-9\-._~+/]{20,}/i;[...W];let L=/\b(?:psql|mysql|sqlite3|pgcli|clickhouse-client)\b/,F=/\b(?:DROP\s+(?:TABLE|DATABASE|SCHEMA)|TRUNCATE\b)/i,q=/\bDELETE\s+FROM\b/i,H=/\bWHERE\b/i,J=/\bALTER\s+TABLE\b[\s\S]*\b(?:DROP\s+COLUMN|ADD\s+COLUMN|RENAME\s+(?:COLUMN|TO)|MODIFY\s+COLUMN)\b/i,G=/(?:npm\s+publish|bun\s+publish|pnpm\s+publish|yarn\s+npm\s+publish|twine\s+upload|poetry\s+publish|cargo\s+publish|gem\s+push)\b/,Y=/(?:^|\s|;|&&|\|\|)(?:env|printenv)(?:\s|$|;|&&|\|)/,Z=/echo\s+.*\$\{?[A-Za-z_]/,K=/(?:^|\s|;|&&|\|\|)export\s+\w+/,Q=/\$env:[A-Za-z_]/i,V=/(?:Get-ChildItem|dir|gci|ls)\s+Env:/i,X=/\[Environment\]::GetEnvironment/i,ee=/echo\s+%[A-Za-z_]/i,et=/(?:^|[\\/])\.env(?:\.|$)/,ei=/\.env(?:\b|\s|$|\.)/,en=/Start-Process\s+.*-Verb\s+RunAs/i,eo=/(?:^|;|&&|\|\|)\s*runas\s/i,es=/(?:curl|wget)\s.*\|\s*(?:sh|bash|zsh|dash|ksh|csh|tcsh|fish|ash)\b/,er=/[;&|\n\r(){}`]+/,ea=new Set(["npx","bunx","pnpx","npm","pnpm","yarn","dlx","exec","run","eval","node","bun","deno","env","command","builtin","nohup","setsid","time","timeout","nice","stdbuf","xargs","sudo","doas","sh","bash","zsh","dash","ksh","fish","ash"]),el=/(?:^|\/)failproofai[^/]*$/,ec=/failproofai\/(?:dist\/(?:cli|index)\.mjs|bin\/failproofai\.mjs)$/,ed=/^(?:config|configure|setup)$/,ep=/^--pause(?:=|$)/,eu=/^[A-Za-z_][A-Za-z0-9_]*=/,em=/^\d+[a-z]*$/i;function ef(e){let t=e.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,"$$$1"),i=null,n=new Set;for(let[,e,i]of t.matchAll(/(?:^|[\s;&|])([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|]+)/g)){let t=i.replace(/^["']|["']$/g,"");(el.test(t)||ec.test(t))&&n.add(e)}let o=e=>{let t=/^\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?$/.exec(e);return!!t&&n.has(t[1])};for(let e of t.split(er)){let t=e.split(/\s+/).filter(Boolean),n=0;for(;n<t.length;){let e=t[n];if(!(eu.test(e)||e.startsWith("-")||e.startsWith(">")||e.startsWith("<")||em.test(e)||ea.has(e.slice(e.lastIndexOf("/")+1))))break;n++}if(n>=t.length||!el.test(t[n])&&!ec.test(t[n])&&!o(t[n]))continue;let s=t.slice(n+1),r=s.findIndex(e=>ed.test(e));if(-1!==r&&s.slice(r+1).some(e=>ep.test(e)))return"pause";i="cli"}return i}let eh=/(?:Invoke-WebRequest|iwr|Invoke-RestMethod|irm)\s+.*\|\s*(?:Invoke-Expression|iex)/i,eg=/^-[a-zA-Z]*f[a-zA-Z]*$/,ey=["--force-with-lease","--force-if-includes"],eb=/\.(?:pem|key)$/,ew=/id_rsa/,ek=/credentials/,ev=/git\s+(commit|merge|rebase|cherry-pick)\b/,eN=/\b(?:rm|unlink|shred|mv|truncate)\b[^;&|]*\.failproofai(?:\/|\b)/,eS=/(?:npm\s+(?:uninstall|remove|un|r)\s.*failproofai|bun\s+remove\s.*failproofai|yarn\s+global\s+remove\s+failproofai|pnpm\s+(?:remove|uninstall|un)\s.*failproofai)/,eT=/\bgit\s+commit\b.*--amend\b/,e$=/\bgit\s+stash\s+(?:drop|clear)\b/,eP=/\bgit\s+add\s+(?:-A\b|--all\b|\.(?:\s|$|;|&&|\|\|))/,eE=/\bnpm\s+(?:install|i)\b(?=.*(?:\s-g\b|--global\b))/,eC=/\byarn\s+global\s+add\b/,eI=/\bpnpm\s+(?:add|install|i)\b(?=.*(?:\s-g\b|--global\b))/,eA=/\bbun\s+(?:install|add)\b(?=.*(?:\s-g\b|--global\b))/,ex=/\bcargo\s+install\b/,eR=/\bpip(?:3)?\s+install\b(?=.*(?:--user\b|--break-system-packages\b))/,eO={pip:[/\bpip\b/,/\bpip3\b/,/\bpython3?\s+-m\s+pip\b/],npm:[/\bnpm\b/,/\bnpx\b/],yarn:[/\byarn\b/],pnpm:[/\bpnpm\b/,/\bpnpx\b/],bun:[/\bbun\b/,/\bbunx\b/],uv:[/\buv\b/],poetry:[/\bpoetry\b/],pipenv:[/\bpipenv\b/],conda:[/\bconda\b/],cargo:[/\bcargo\b/]},e_=/\bnohup\s+\S/,ej=/\bscreen\s+-[A-Za-z]*d[A-Za-z]*\b/,eB=/\btmux\s+(?:new-session|new)\b[^|&;]*-d\b/,eD=/\bdisown\b/,eW=/(?<![&|])\s?&\s*(?:$|#|;)/,eM=/(?:^|[;\n]|&&|\|\|?|&)\s*kubectl(?:\s|$)/,eU=/(?:^|[;\n]|&&|\|\|?|&)\s*(?:terraform|tofu)(?:\s|$)/,ez=/(?:^|[;\n]|&&|\|\|?|&)\s*aws(?:\s|$)/,eL=/(?:^|[;\n]|&&|\|\|?|&)\s*gcloud(?:\s|$)/,eF=/(?:^|[;\n]|&&|\|\|?|&)\s*az(?:\s|$)/,eq=/(?:^|[;\n]|&&|\|\|?|&)\s*helm(?:\s|$)/,eH=/(?:^|[;\n]|&&|\|\|?|&)\s*gh\s+(?:workflow\s+(?:run|enable|disable)|run\s+(?:rerun|cancel)|pr\s+merge|release\s+(?:create|delete)|cache\s+delete|secret\s+(?:set|delete))\b/,eJ=new Map;function eG(e){try{let t=function(e){try{return(0,o.statSync)((0,n.join)(e,".git","HEAD")).mtimeMs}catch{return null}}(e),i=eJ.get(e);if(i&&null!==t&&i.headMtimeMs===t)return i.branch||null;let s=(0,r.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}).trim();return null!==t&&(eJ.size>=500&&eJ.clear(),eJ.set(e,{branch:s,headMtimeMs:t})),s||null}catch{return null}}function eY(e,t){let i=_(e),n=_(t);return!(i.length<n.length||i.some(e=>j.has(e))||i.some(e=>B.test(e)))&&n.every((e,t)=>"*"===e||e===i[t])}let eZ=/^-{1,2}c$/;function eK(e){return e.split(/&&|\|\||[|;\n]/).map(e=>e.trim()).filter(e=>/^git\s+push\s/.test(e)).map(e=>e.replace(/^git\s+push\s+/,""))}let eQ=/^(?:~[A-Za-z0-9_.-]*|\$HOME|\$\{HOME\})(?=$|\/)/,eV=/^(?:\/\S*\/)?rm$/,eX=/^(?:\/\S*\/)?find$/,e0=/^-(?:exec|execdir|ok|okdir)$/,e1=/^-(?:[HLP]|D|O\d*)$/,e3=/^(?:-|\\?[(!])/,e8=["/tmp","/var/tmp"];function e9(e){let t=e.match(/^(?:~|\$HOME|\$\{HOME\})(?=$|\/)/);return t?(0,a.homedir)()+e.slice(t[0].length):e}function e6(e){return e.replace(/\/\*$/,"").replace(/\/+$/,"")}function e2(e){let t=e.replace(/^['"]|['"]$/g,"");if(""===t)return!1;let i=t.match(eQ);if(!i&&/^[$`]/.test(t))return!0;let n=i?t.slice(i[0].length):t.startsWith("/")?t:null;if(null===n)return!1;let o=e6(n).split("/").filter(Boolean);return!(!i&&e8.some(e=>`/${o.join("/")}`.startsWith(`${e}/`)))&&o.length<=2}function e4(e){let t=_(e),i=t.findIndex(e=>eX.test(e));if(i>=0){let e=t.slice(i+1),n=e.findIndex(e=>e0.test(e));if(e.includes("-delete")||n>=0&&eV.test(e[n+1]??"")){let t=0;for(;t<e.length&&e1.test(e[t]);)t+="-D"===e[t]?2:1;let i=e.slice(t),n=i.findIndex(e=>e3.test(e));return n<0?i:i.slice(0,n)}}let n=t.findIndex(e=>eV.test(e));if(n>=0){let e=t.slice(n+1),i=e.filter(e=>/^-[^-]/.test(e)).join(""),o=e.filter(e=>/^--/.test(e)),s=/r/i.test(i)||o.some(e=>/^--recursive$/i.test(e)),r=/f/.test(i)||o.some(e=>/^--force$/i.test(e));if(s&&r)return e.filter(e=>!e.startsWith("-"))}return null}function e5(e){return e.split(/&&|\|\||[|;\n]/).map(e=>e.trim()).filter(e=>""!==e)}let e7=/(?:^|;|&&|\|\||\|)\s*(?:ls|find|cat|head|tail|less|more|wc|file|stat|tree|du)\s/;function te(e,t,i){if("Bash"!==e.toolName)return c();let n=R(e);return!t.test(n)||(e.params?.allowPatterns??[]).some(e=>eY(n,e))?c():d(i)}let tt=/\s*(?:&&|\|\||\||;)\s*/;function ti(e){return e.session?.permissionMode==="plan"}let tn={"sanitize-jwt":function(e){let t=JSON.stringify(e.payload);return D.test(t)?{decision:"deny",reason:"JWT token detected in tool output",message:"[REDACTED: JWT token removed by failproofai]"}:c()},"sanitize-api-keys":function(e){let t=JSON.stringify(e.payload);for(let[e,i]of W)if(e.test(t))return{decision:"deny",reason:`${i} detected in tool output`,message:`[REDACTED: ${i} removed by failproofai]`};for(let{regex:i,label:n}of e.params?.additionalPatterns??[])try{if(new RegExp(i).test(t))return{decision:"deny",reason:`${n} detected in tool output`,message:`[REDACTED: ${n} removed by failproofai]`}}catch{I(`additionalPatterns: invalid regex "${i}", skipping`)}return c()},"sanitize-connection-strings":function(e){let t=JSON.stringify(e.payload);return M.test(t)?{decision:"deny",reason:"Database connection string with credentials detected in tool output",message:"[REDACTED: connection string removed by failproofai]"}:c()},"sanitize-private-key-content":function(e){let t=JSON.stringify(e.payload);return U.test(t)?{decision:"deny",reason:"Private key content detected in tool output",message:"[REDACTED: private key content removed by failproofai]"}:c()},"sanitize-bearer-tokens":function(e){let t=JSON.stringify(e.payload);return z.test(t)?{decision:"deny",reason:"Bearer token detected in tool output",message:"[REDACTED: Bearer token removed by failproofai]"}:c()},"protect-env-vars":function(e){if("Bash"!==e.toolName)return c();let t=R(e);return Y.test(t)?d("Command reads environment variables"):Z.test(t)?d("Command echoes environment variable"):K.test(t)?d("Command exports environment variable"):Q.test(t)?d("Command reads environment variable via PowerShell"):V.test(t)?d("Command reads environment variables via PowerShell"):X.test(t)?d("Command reads environment variable via .NET"):ee.test(t)?d("Command echoes environment variable via cmd"):c()},"block-env-files":function(e){let t=R(e),i=O(e);return i&&et.test(i)?d("Access to .env file blocked"):"Bash"===e.toolName&&ei.test(t)?d("Command references .env file"):c()},"block-read-outside-cwd":function(e){let t=process.env.CLAUDE_PROJECT_DIR||e.session?.cwd;if(!t)return c();let i=e.params?.allowPaths??[];if("Bash"===e.toolName){let o=R(e);if(!e7.test(o))return c();let s=function(e){let t,i=[],o=/(?<![a-zA-Z0-9_.\-~\\*?:=])(?:~\/[^\s;|&"'()\[\]{}]*|~(?=\s|$|[;|&"'()\[\]{}])|\/[^\s;|&"'()\[\]{}]*)/g;function s(e){let t;for(o.lastIndex=0;null!==(t=o.exec(e));){let e=t[0];"~"===e?e=(0,a.homedir)():e.startsWith("~/")&&(e=(0,n.join)((0,a.homedir)(),e.slice(2))),i.push(e)}}let r=e.length,l=!1,c=!1;for(let t=0;t<e.length;t++){let i=e[t];if('"'!==i||c)if("'"!==i||l){if("|"===i&&!l&&!c){r=t;break}}else c=!c;else l=!l}let d=e.slice(0,r),p=/"([^"]*)"|'([^']*)'/g;for(;null!==(t=p.exec(d));){let e=t[1]??t[2]??"";/[*?\[\]^$+()\\]/.test(e)||s(e)}return s(e.replace(/"[^"]*"/g,e=>" ".repeat(e.length)).replace(/'[^']*'/g,e=>" ".repeat(e.length))),i}(o),r=t.endsWith("/")?t:t+"/";for(let e of s){let o=(0,n.resolve)(t,e);if(x(o))return d(`Reading agent settings file blocked: ${o}`);if(!A(o)&&"/dev/null"!==o&&o!==t&&!o.startsWith(r)){if(i.some(e=>o===e||o.startsWith(e.endsWith("/")?e:e+"/")))continue;return d(`Bash read outside project directory blocked: ${o}`)}}return c()}let o=O(e),s=e.toolInput?.path??"",r=o||s;if(!r)return c();let l=(0,n.resolve)(t,r);if(x(l))return d(`Reading agent settings file blocked: ${l}`);if(A(l)||"/dev/null"===l)return c();let p=t.endsWith("/")?t:t+"/";return l===t||l.startsWith(p)?c():i.some(e=>l===e||l.startsWith(e.endsWith("/")?e:e+"/"))?c():d(`Access outside project directory blocked: ${l}`)},"block-sudo":function(e){if("Bash"!==e.toolName)return c();let t=R(e).trimStart();return function e(t,i=0){for(let n of function(e){let t=[],i=[],n="",o=null,s=()=>{n&&i.push(n),n=""},r=()=>{s(),i.length&&t.push(i),i=[]};for(let t=0;t<e.length;t++){let i=e[t];if(o){if("\\"===i&&'"'===o&&t+1<e.length){n+=e[++t];continue}if(i===o){o=null;continue}n+=i;continue}if("\\"===i&&t+1<e.length){n+=e[++t];continue}if('"'===i||"'"===i){o=i;continue}if(/\s/.test(i)){s();continue}if(/[;&|\n\r(){}`]/.test(i)){r();continue}n+=i}return r(),t}(t)){let t=0;for(;t<n.length;){let o=n[t],s=o.slice(o.lastIndexOf("/")+1);if("sudo"===s||"doas"===s)return!0;if(!(eu.test(o)||o.startsWith("-")||o.startsWith(">")||o.startsWith("<")||em.test(o)||ea.has(s)))break;if(eZ.test(o)&&i<3&&t+1<n.length&&e(n[t+1],i+1))return!0;t++}}return!1}(t)?(e.params?.allowPatterns??[]).some(e=>eY(t,e))?c():d("sudo commands are blocked"):en.test(t)?d("Elevated process launch is blocked"):eo.test(t)?d("runas elevation is blocked"):c()},"block-curl-pipe-sh":function(e){if("Bash"!==e.toolName)return c();let t=R(e);return es.test(t)?d("Piping downloads to shell is blocked"):eh.test(t)?d("Piping downloads to Invoke-Expression is blocked"):c()},"block-rm-rf":function(e){if("Bash"!==e.toolName)return c();let t=R(e);return e5(t).some(e=>{let t=e4(e);return null!==t&&t.some(e2)})?!function(e,t){if(0===t.length)return!1;let i=t.map(e=>e6(e9(e))||"/"),n=!1;for(let o of e5(e)){let e=e4(o);if(null!==e)for(let s of(n=!0,e)){let e=e6(e9(s))||"/";if(!i.some(t=>e===t||e.startsWith(t+"/"))&&!t.some(e=>{let t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return RegExp(`${t}(?:[/"'\\s/*]|$)`).test(o)}))return!1}}return n}(t,e.params?.allowPaths??[])?d("Catastrophic deletion blocked"):c():/Remove-Item\s+.*-Recurse.*-Force.*(?:[A-Z]:\\(?:\s|$)|\\\*)/i.test(t)||/(?:rd|rmdir)\s+\/s\s+\/q\s+[A-Z]:\\/i.test(t)?d("Catastrophic deletion blocked"):c()},"block-failproofai-commands":function(e){if("Bash"!==e.toolName)return c();let t=R(e),i=t.replace(/\\\r?\n/g,"").replace(/\$'((?:[^'\\]|\\.)*)'/g,(e,t)=>t.replace(/\\(x[0-9A-Fa-f]{1,2}|u[0-9A-Fa-f]{1,4}|U[0-9A-Fa-f]{1,8}|[0-7]{1,3}|.)/g,(e,t)=>{try{if("x"===t[0])return String.fromCharCode(parseInt(t.slice(1),16));if("u"===t[0]||"U"===t[0])return String.fromCodePoint(parseInt(t.slice(1),16));if(/^[0-7]+$/.test(t))return String.fromCharCode(parseInt(t,8))}catch{return t}return({a:"\x07",b:"\b",e:"\x1b",f:"\f",n:"\n",r:"\r",t:" ",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"})[t]??t})).replace(/\\(.)/g,"$1").replace(/['"]/g,""),n=ef(t)??ef(i);return"pause"===n?d("Pausing failproofai enforcement is a human action, not an agent one. If a policy is blocking legitimate work, say so and let the operator decide."):"cli"===n?d("Running failproofai CLI commands is blocked"):eS.test(t)||eS.test(i)?d("Uninstalling failproofai is blocked"):eN.test(t)||eN.test(i)?d("Deleting or moving failproofai's own state would switch enforcement off. If a policy is blocking legitimate work, say so and let the operator decide."):c()},"block-kubectl":function(e){return te(e,eM,"kubectl commands are blocked")},"block-terraform":function(e){return te(e,eU,"terraform/tofu commands are blocked")},"block-aws-cli":function(e){return te(e,ez,"aws CLI commands are blocked")},"block-gcloud":function(e){return te(e,eL,"gcloud commands are blocked")},"block-az-cli":function(e){return te(e,eF,"az (Azure) CLI commands are blocked")},"block-helm":function(e){return te(e,eq,"helm commands are blocked")},"block-gh-pipeline":function(e){return te(e,eH,"gh pipeline-trigger commands are blocked")},"block-secrets-write":function(e){if("Write"!==e.toolName)return c();let t=O(e);if(eb.test(t)||ew.test(t)||ek.test(t))return d("Writing secret key files is blocked");for(let i of e.params?.additionalPatterns??[])if(t.includes(i))return d(`Writing blocked file pattern: ${i}`);return c()},"block-push-master":function(e){if("Bash"!==e.toolName)return c();let t=e.params?.protectedBranches??["main","master"];if(0===t.length)return c();let i=eK(R(e)),n=RegExp(`\\b(?:${t.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|")})\\b`);return i.some(e=>n.test(e))?d(`Pushing to ${t.join("/")} is blocked`):c()},"block-force-push":function(e){if("Bash"!==e.toolName)return c();for(let t of eK(R(e))){let e=!1;for(let i of t.split(/\s+/)){if("--"===i){e=!0;continue}if(!e&&function(e){return"--force"===e||!ey.some(t=>e.startsWith(t))&&(!!e.startsWith("--force")||eg.test(e))}(i))return d("Force-pushing is blocked")}}return c()},"block-work-on-main":function(e){if("Bash"!==e.toolName)return c();let t=R(e).match(ev);if(!t)return c();let i=e.session?.cwd;if(!i)return c();let n=eG(i);return n&&(e.params?.protectedBranches??["main","master"]).includes(n)?d(`Git ${t[1]} on ${n} is blocked. Create a feature branch first.`):c()},"warn-git-amend":function(e){if("Bash"!==e.toolName)return c();let t=R(e);return eT.test(t)?p("STOP: This command amends the last commit, which rewrites git history. If this commit has already been pushed to a shared branch, this will cause divergence for other contributors. Confirm with the user before executing."):c()},"warn-git-stash-drop":function(e){if("Bash"!==e.toolName)return c();let t=R(e);return e$.test(t)?p("STOP: This command permanently deletes stashed changes (git stash drop/clear). Stash entries cannot be recovered after deletion. Confirm with the user before executing."):c()},"warn-all-files-staged":function(e){if("Bash"!==e.toolName)return c();let t=R(e);return eP.test(t)?p("STOP: This command stages all files in the working tree (git add -A / --all / .). This may inadvertently include build artifacts, generated files, or sensitive files not covered by .gitignore. Confirm with the user before executing."):c()},"warn-destructive-sql":function(e){if("Bash"!==e.toolName)return c();let t=R(e);return L.test(t)&&(F.test(t)||q.test(t)&&!H.test(t))?p("STOP: This command contains destructive SQL (DROP/TRUNCATE/DELETE). Confirm with the user before executing."):c()},"warn-schema-alteration":function(e){if("Bash"!==e.toolName)return c();let t=R(e);return L.test(t)&&J.test(t)?p("STOP: This command contains a schema-altering SQL statement (ALTER TABLE with column or rename operation). Schema changes on production databases are irreversible or disruptive. Confirm with the user before executing."):c()},"warn-package-publish":function(e){if("Bash"!==e.toolName)return c();let t=R(e);return G.test(t)?p("STOP: This command publishes a package to a public registry. Confirm with the user that this is intentional."):c()},"warn-global-package-install":function(e){if("Bash"!==e.toolName)return c();let t=R(e);return eE.test(t)||eC.test(t)||eI.test(t)||eA.test(t)||ex.test(t)||eR.test(t)?p("STOP: This command installs a package globally, which modifies the system-wide environment outside the project. This can conflict with other projects or system tools. Confirm with the user before executing."):c()},"prefer-package-manager":function(e){if("Bash"!==e.toolName)return c();let t=R(e);if(!t)return c();let i=e.params?.allowed??[];if(0===i.length)return c();let n=new Set(i.map(e=>e.toLowerCase())),o=e.params?.blocked??[],s=i.join(", ");for(let e of t.split(tt)){let t=e.trim();if(!t)continue;let i=!1;for(let e of n){let n=eO[e];if(n){for(let e of n)if(e.test(t)){i=!0;break}if(i)break}}if(!i){for(let[e,i]of Object.entries(eO))if(!n.has(e)){for(let n of i)if(n.test(t))return d(`"${e}" is not an allowed package manager. Allowed package managers for this project: ${s}. Rewrite this command using an allowed package manager.`)}for(let e of o){let i=e.toLowerCase();if(!n.has(i)&&RegExp(`\\b${i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`).test(t))return d(`"${i}" is not an allowed package manager. Allowed package managers for this project: ${s}. Rewrite this command using an allowed package manager.`)}}}return c()},"warn-large-file-write":function(e){if("Write"!==e.toolName)return c();let t=e.toolInput?.content;if("string"!=typeof t)return c();let i=e.params?.thresholdKb??1024;return t.length>1024*i?p(`STOP: You are writing a file larger than ${i}KB (${Math.round(t.length/1024)}KB). This is unusually large. Confirm this is intentional before proceeding.`):c()},"warn-background-process":function(e){if("Bash"!==e.toolName)return c();let t=R(e);return e_.test(t)||ej.test(t)||eB.test(t)||eD.test(t)||eW.test(t)?p("STOP: This command starts a background or detached process (nohup, screen -d, tmux -d, or trailing &). Background processes persist after Claude's session and may be difficult to track or stop. Confirm with the user before executing."):c()},"warn-repeated-tool-calls":async function e(e){let t=e.session?.transcriptPath;if(!t||!e.toolName||!e.toolInput)return c();let i=`${t}.tool-calls.json`,n=JSON.stringify({tool:e.toolName,input:e.toolInput}),o={};try{let e=await (0,s.readFile)(i,"utf8");o=JSON.parse(e)}catch{}let r=o[n]??0;if(r>=3)return p(`STOP: You have already called ${e.toolName} ${r} times with identical parameters. This is wasteful and unproductive. Do NOT repeat this call — use a different approach or ask the user for clarification.`);o[n]=r+1;try{let e=JSON.stringify(o);e.length<=65536&&await (0,s.writeFile)(i,e,"utf8")}catch{}return c()},"require-commit-before-stop":function(e){if(ti(e))return c("Plan mode — no changes made, skipping commit check.");let t=e.session?.cwd;if(!t)return c("No working directory available, skipping commit check.");try{if((0,r.execSync)("git status --porcelain",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().length>0)return d("You have uncommitted changes in the working directory. Commit all changes now.");return c("All changes are committed.")}catch{return c("Not a git repository, skipping commit check.")}},"require-push-before-stop":function(e){if(ti(e))return c("Plan mode — no changes made, skipping push check.");let t=e.session?.cwd;if(!t)return c("No working directory available, skipping push check.");try{if(!(0,r.execSync)("git remote",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}).trim())return c("No git remote configured, skipping push check.");let i=e.params?.remote??"origin",n=eG(t);if(!n||"HEAD"===n)return c("Detached HEAD, skipping push check.");let o=e.params?.baseBranch??"main";if(n===o)return c(`On base branch "${o}", skipping push check.`);try{if(!(0,r.execFileSync)("git",["log",`${i}/${o}..HEAD`,"--oneline"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim())return c(`No commits ahead of ${i}/${o}, skipping push check.`);if(!(0,r.execFileSync)("git",["diff","--stat",`${i}/${o}`,"HEAD"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim())return c(`No file changes compared to ${i}/${o}, skipping push check.`)}catch{}let s=!1;try{(0,r.execFileSync)("git",["rev-parse","--verify",`${i}/${n}`],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}),s=!0}catch{}if(!s)return d(`Branch "${n}" has not been pushed to remote "${i}". Run now: git push -u ${i} ${n}`);let a=(0,r.execFileSync)("git",["log",`${i}/${n}..HEAD`,"--oneline"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim();if(a.length>0){let e=a.split("\n").length;return d(`You have ${e} unpushed commit${e>1?"s":""} on branch "${n}". Run now: git push`)}return c(`All commits pushed to "${i}".`)}catch{return c("Could not check push status, skipping.")}},"require-pr-before-stop":function(e){if(ti(e))return c("Plan mode — no changes made, skipping PR check.");let t=e.session?.cwd;if(!t)return c("No working directory available, skipping PR check.");try{let i;try{(0,r.execSync)("gh --version",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3})}catch{return c("GitHub CLI (gh) not installed, skipping PR check.")}let n=eG(t);if(!n||"HEAD"===n)return c("Detached HEAD, skipping PR check.");let o=e.params?.baseBranch??"main";if(n===o)return c(`On base branch "${o}", skipping PR check.`);try{if(!(0,r.execFileSync)("git",["log",`origin/${o}..HEAD`,"--oneline"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim())return c(`No commits ahead of origin/${o}, skipping PR check.`);if(!(0,r.execFileSync)("git",["diff","--stat",`origin/${o}`,"HEAD"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim())return c(`No file changes compared to origin/${o}, skipping PR check.`)}catch{}try{i=(0,r.execSync)("gh pr view --json number,url,state",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:15e3}).trim()}catch{return d(`No pull request found for branch "${n}". Run now: gh pr create`)}let s=JSON.parse(i);if("OPEN"===s.state)return c(`PR #${s.number} exists: ${s.url}`);if("MERGED"===s.state)return c(`PR #${s.number} was merged: ${s.url}. Switch off this branch (e.g. 'git checkout ${o} && git pull') before stopping again.`);return d(`Pull request for branch "${n}" is ${s.state.toLowerCase()}. Run now: gh pr create`)}catch{return c("Could not check PR status, skipping.")}},"require-no-conflicts-before-stop":function(e){let t,i;if(ti(e))return c("Plan mode — no changes made, skipping conflict check.");let n=e.session?.cwd;if(!n)return c("No working directory available, skipping conflict check.");let o=eG(n);if(!o||"HEAD"===o)return c("Detached HEAD, skipping conflict check.");let s=e.params?.baseBranch??"main";if(o===s)return c(`On base branch "${s}", skipping conflict check.`);try{(0,r.execSync)("gh --version",{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3})}catch{return c("gh CLI not installed, skipping conflict check.")}try{t=(0,r.execSync)("gh pr view --json mergeable,number,url,state",{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:15e3}).trim()}catch{return c("No pull request found for branch, skipping conflict check.")}try{i=JSON.parse(t)}catch{return c("Could not parse gh pr view output, skipping conflict check.")}if("OPEN"!==i.state)return c(`PR #${i.number} is ${i.state.toLowerCase()}; skipping conflict check.`);try{(0,r.execFileSync)("git",["rev-parse","--verify",`origin/${s}`],{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}),(0,r.execFileSync)("git",["log",`origin/${s}..HEAD`,"--oneline"],{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim()&&(0,r.execFileSync)("git",["merge-tree","--write-tree","--name-only",`origin/${s}`,"HEAD"],{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:1e4})}catch(e){if(1===e.status){let t=("string"==typeof e.stdout?e.stdout:e.stdout?.toString("utf8")??"").trim().split("\n"),i=[];for(let e=1;e<t.length;e++){let n=t[e];if(""===n)break;i.push(n)}let n=i.length?i.join(", "):"one or more files";return d(`Branch "${o}" has merge conflicts with ${s} in: ${n}. Rebase or merge origin/${s} now and resolve the conflicts.`)}}return"CONFLICTING"===i.mergeable?d(`PR #${i.number} has merge conflicts per GitHub (${i.url}). Rebase or merge origin/${s} now and resolve the conflicts.`):"UNKNOWN"===i.mergeable?d(`GitHub is still computing mergeability for PR #${i.number} (${i.url}). Wait ~10 seconds, then re-check with \`gh pr view --json mergeable\` before attempting to stop again.`):c(`PR #${i.number} merges cleanly per GitHub.`)},"require-ci-green-before-stop":function(e){if(ti(e))return c("Plan mode — no changes made, skipping CI check.");let t=e.session?.cwd;if(!t)return c("No working directory available, skipping CI check.");try{try{(0,r.execSync)("gh --version",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3})}catch{return c("GitHub CLI (gh) not installed, skipping CI check.")}let e=eG(t);if(!e||"HEAD"===e)return c("Detached HEAD, skipping CI check.");let i=function(e){try{return(0,r.execSync)("git rev-parse HEAD",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:3e3}).trim()||null}catch{return null}}(t),n=[];try{let o=(0,r.execFileSync)("gh",["run","list","--branch",e,"--limit","20","--json","status,conclusion,name,headSha"],{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:15e3}).trim();if(o&&"[]"!==o){let e=JSON.parse(o),t=i?e.filter(e=>e.headSha===i):e,s=new Set;n=t.filter(e=>!s.has(e.name)&&(s.add(e.name),!0))}}catch{}let o=[],s=[];i&&(o=function(e,t){try{let i=(0,r.execFileSync)("gh",["api",`repos/{owner}/{repo}/commits/${t}/check-runs`,"--jq",'.check_runs | map(select(.app.slug != "github-actions")) | map({name: .name, status: .status, conclusion: (.conclusion // "")})'],{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:15e3}).trim();if(!i||"[]"===i)return[];return JSON.parse(i)}catch{return[]}}(t,i),s=function(e,t){try{let i=(0,r.execFileSync)("gh",["api",`repos/{owner}/{repo}/commits/${t}/statuses`,"--jq","map({name: .context, state: .state}) | unique_by(.name)"],{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:15e3}).trim();if(!i||"[]"===i)return[];return JSON.parse(i).map(e=>({name:e.name,status:"pending"===e.state?"in_progress":"completed",conclusion:"pending"===e.state?"":"success"===e.state?"success":"failure"}))}catch{return[]}}(t,i));let a=[...n,...o,...s];if(0===a.length)return c(`No CI runs found for branch "${e}".`);let l=a.filter(e=>"completed"===e.status&&"success"!==e.conclusion&&"skipped"!==e.conclusion&&"cancelled"!==e.conclusion&&"neutral"!==e.conclusion);if(l.length>0){let t=l.map(e=>`"${e.name}"`).join(", ");return d(`CI checks are failing on branch "${e}": ${t}. Fix the failing checks now.`)}let p=a.filter(e=>"in_progress"===e.status||"queued"===e.status||"waiting"===e.status);if(p.length>0){let t=p.map(e=>`"${e.name}"`).join(", ");return d(`CI checks are still running on branch "${e}": ${t}. Wait for all checks to complete, then verify they pass.`)}return c(`All CI checks passed on branch "${e}".`)}catch{return c("Could not check CI status, skipping.")}}},to=new Set(Object.keys(tn)),ts=l.filter(e=>!to.has(e.name)).map(e=>e.name);if(ts.length>0)throw Error(`failproofai: builtin policies missing an implementation: ${ts.join(", ")}`);let tr=new Set(l.map(e=>e.name)),ta=[...to].filter(e=>!tr.has(e));if(ta.length>0)throw Error(`failproofai: policy implementations with no catalog entry: ${ta.join(", ")}`);let tl=l.map(e=>({...e,fn:tn[e.name]}));function tc(e){if(!(0,o.existsSync)(e))return{};try{let t=(0,o.readFileSync)(e,"utf8");return JSON.parse(t)}catch(t){return I(`failed to parse config at ${e}: ${t instanceof Error?t.message:String(t)}`),{}}}let td=["claude","codex","copilot","cursor","opencode","pi","hermes","openclaw","factory","devin","antigravity","goose"],tp={apply_patch:"Edit",write_stdin:"Bash"},tu={terminal:"Bash",bash:"Bash",read_file:"Read",write_file:"Write",patch:"Edit",web_search:"WebSearch",web_extract:"WebFetch",search_files:"Grep",todo:"TodoWrite"},tm={Read:{path:"file_path"},Write:{path:"file_path"},Edit:{path:"file_path"}},tf={bash:"Bash",powershell:"Bash",list_bash:"Bash",read_bash:"Bash",stop_bash:"Bash",write_bash:"Bash",list_powershell:"Bash",read_powershell:"Bash",stop_powershell:"Bash",write_powershell:"Bash",read:"Read",view:"Read",show_file:"Read",write:"Write",create:"Write",edit:"Edit",apply_patch:"Edit",str_replace_editor:"Edit",glob:"Glob",grep:"Grep",rg:"Grep",ls:"LS",web_fetch:"WebFetch"},th={Read:{path:"file_path"},Write:{path:"file_path",file_text:"content"},Edit:{path:"file_path",old_str:"old_string",new_str:"new_string"}},tg={Shell:"Bash"},ty={bash:"Bash",read:"Read",write:"Write",edit:"Edit",apply_patch:"Edit",glob:"Glob",grep:"Grep",list:"LS",webfetch:"WebFetch",websearch:"WebSearch",todowrite:"TodoWrite",todoread:"TodoRead"},tb={Read:{filePath:"file_path"},Write:{filePath:"file_path"},Edit:{filePath:"file_path",oldString:"old_string",newString:"new_string",replaceAll:"replace_all"}},tw={bash:"Bash",read:"Read",write:"Write",edit:"Edit",glob:"Glob",grep:"Grep"},tk={Read:{path:"file_path"},Write:{path:"file_path"},Edit:{path:"file_path"}},tv={exec:"Bash",read:"Read",write:"Write",edit:"Edit",grep:"Grep",glob:"Glob",web_search:"WebSearch",web_fetch:"WebFetch"},tN={Read:{path:"file_path"},Write:{path:"file_path"},Edit:{path:"file_path"}},tS={Execute:"Bash",Read:"Read",Edit:"Edit",Create:"Write",Grep:"Grep",Glob:"Glob",LS:"LS",FetchUrl:"WebFetch",WebSearch:"WebSearch",TodoWrite:"TodoWrite",Task:"Task"},tT={exec:"Bash"},t$={run_command:"Bash",write_to_file:"Write",read_file:"Read",view_file:"Read",edit_file:"Edit",replace_file_content:"Edit",list_dir:"LS",find_by_name:"Glob",grep_search:"Grep",read_url_content:"WebFetch",search_web:"WebSearch"},tP={Bash:{CommandLine:"command",Cwd:"cwd"},Write:{TargetFile:"file_path",CodeContent:"content"},Edit:{TargetFile:"file_path"},Read:{TargetFile:"file_path",AbsolutePath:"file_path",File:"file_path"}},tE={shell:"Bash",write:"Write",edit:"Edit",view:"Read",read_image:"Read",glob:"Glob",grep:"Grep",tree:"LS",delegate:"Task",todo__todo_write:"TodoWrite"},tC={Read:{path:"file_path",source:"file_path"},Write:{path:"file_path"},Edit:{path:"file_path"},LS:{path:"file_path"}};["SessionStart","SessionEnd","UserPromptSubmit","PreToolUse","PermissionRequest","PermissionDenied","PostToolUse","PostToolUseFailure","Notification","SubagentStart","SubagentStop","TaskCreated","TaskCompleted","Stop","StopFailure","TeammateIdle","InstructionsLoaded","ConfigChange","CwdChanged","FileChanged","WorktreeCreate","WorktreeRemove","PreCompact","PostCompact","Elicitation","ElicitationResult","UserPromptExpansion","PostToolBatch","Setup"].filter(e=>"WorktreeCreate"!==e);var tI=e.i(81580);let tA=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;var tx=e.i(54214);function tR(e,t){let i=[];for(let o of e)if("assistant"===o.type)for(let e of o.message.content){var n;let s;if("tool_use"!==e.type)continue;let r=e.name,a=(n=t.cli,(r?"copilot"===n?tf[r]??r:"cursor"===n?tg[r]??r:"codex"===n?tp[r]??r:"opencode"===n?ty[r]??r:"pi"===n?tw[r]??r:"hermes"===n?tu[r]??r:"openclaw"===n?tv[r]??r:"factory"===n?tS[r]??r:"devin"===n?tT[r]??r:"antigravity"===n?t$[r]??r:"goose"===n?tE[r]??r:r:r)??r),l=function(e,t,i){let n;if(!e||!t||"object"!=typeof t||Array.isArray(t)||("copilot"===i?n=th[e]:"opencode"===i?n=tb[e]:"pi"===i?n=tk[e]:"hermes"===i?n=tm[e]:"openclaw"===i?n=tN[e]:"antigravity"===i?n=tP[e]:"goose"===i&&(n=tC[e]),!n))return t;let o={};for(let[e,i]of Object.entries(t))o[n[e]??e]=i;return o}(a,e.input,t.cli);e.result?.content&&(s=function(e){let t=Buffer.from(e,"utf-8");if(t.byteLength<=65536)return e;let i=65536;for(;i>0&&(192&t[i])==128;)i--;return t.subarray(0,i).toString("utf-8")}(e.result.content)),i.push({cli:t.cli,sessionId:t.sessionId,transcriptPath:t.transcriptPath,cwd:t.cwd,timestamp:o.timestamp,toolName:a,rawToolName:r,toolInput:l??{},toolResultText:s})}return i}async function tO(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,s=[];for(let e of function(){let e,t=(0,tI.getClaudeProjectsPath)();try{e=(0,o.readdirSync)(t,{withFileTypes:!0})}catch{return[]}return e.filter(e=>e.isDirectory()).map(e=>({name:e.name,cwd:(0,tI.decodeFolderName)(e.name),path:(0,n.join)(t,e.name)}))}()){let r;if(!t||t.has(e.cwd)){try{r=function(e){let t,i=[];try{t=(0,o.readdirSync)(e.path,{withFileTypes:!0})}catch{return i}for(let s of t)if(s.isFile()&&s.name.endsWith(".jsonl")){let t=s.name.slice(0,-6);if(!tA.test(t))continue;let r=(0,n.join)(e.path,s.name);try{let n=(0,o.statSync)(r);i.push({projectName:e.name,cwd:e.cwd,sessionId:t,transcriptPath:r,mtimeMs:n.mtimeMs,sizeBytes:n.size,isSubagent:!1})}catch{}}else if(s.isDirectory()&&tA.test(s.name)){let t,r=(0,n.join)(e.path,s.name,"subagents");if(!(0,o.existsSync)(r))continue;try{t=(0,o.readdirSync)(r,{withFileTypes:!0})}catch{continue}for(let s of t){if(!s.isFile()||!s.name.endsWith(".jsonl"))continue;let t=s.name.slice(0,-6),a=(0,n.join)(r,s.name);try{let n=(0,o.statSync)(a);i.push({projectName:e.name,cwd:e.cwd,sessionId:t,transcriptPath:a,mtimeMs:n.mtimeMs,sizeBytes:n.size,isSubagent:!0})}catch{}}}return i}(e)}catch{continue}for(let t of r)t.mtimeMs<i||s.push({cli:"claude",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.transcriptPath,mtimeMs:t.mtimeMs,sizeBytes:t.sizeBytes})}}return s}async function t_(e){let t,i;try{t=await (0,s.readFile)(e.transcriptPath,"utf-8")}catch{return[]}try{i=await (0,tx.parseLogContent)(t,"session")}catch{return[]}let n="";for(let e of t.split("\n",50))if(e.trim())try{let t=JSON.parse(e);if("string"==typeof t.cwd&&t.cwd.length>0){n=t.cwd;break}}catch{}return tR(i,{cli:"claude",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:n})}var tj=e.i(36203),tB=e.i(57232);async function tD(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,tj.getCodexProjects)())){let{cwd:s,sessions:r}=await (0,tj.getCodexSessionsByEncodedName)(e.name),a=s??"";if(!t||t.has(a))for(let t of r){let s=t.lastModified.getTime();if(s<i)continue;let r=0;try{r=(0,o.statSync)(t.path).size}catch{}t.sessionId&&n.push({cli:"codex",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:s,sizeBytes:r})}}return n}async function tW(e){let t=await (0,tB.getCodexSessionLog)(e.sessionId);return t?tR(t.entries,{cli:"codex",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tM=e.i(55851),tU=e.i(78166);async function tz(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,tM.getCopilotProjects)())){let{cwd:s,sessions:r}=await (0,tM.getCopilotSessionsByEncodedName)(e.name),a=s??"";if(!t||t.has(a))for(let t of r){let s=t.lastModified.getTime();if(s<i)continue;let r=0;try{r=(0,o.statSync)(t.path).size}catch{}t.sessionId&&n.push({cli:"copilot",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:s,sizeBytes:r})}}return n}async function tL(e){let t=await (0,tU.getCopilotSessionLog)(e.sessionId);return t?tR(t.entries,{cli:"copilot",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tF=e.i(46413),tq=e.i(72094);async function tH(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,tF.getCursorProjects)())){let{cwd:s,sessions:r}=await (0,tF.getCursorSessionsByEncodedName)(e.name),a=s??"";if(!t||t.has(a))for(let t of r){let s=t.lastModified.getTime();if(s<i)continue;let r=0;try{r=(0,o.statSync)(t.path).size}catch{}t.sessionId&&n.push({cli:"cursor",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:s,sizeBytes:r})}}return n}async function tJ(e){let t=await (0,tq.getCursorSessionLog)(e.sessionId);return t?tR(t.entries,{cli:"cursor",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tG=e.i(35435),tY=e.i(99440);async function tZ(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,tG.getOpenCodeProjects)())){let{cwd:o,sessions:s}=await (0,tG.getOpenCodeSessionsByEncodedName)(e.name),r=o??"";if(!t||t.has(r))for(let t of s){let o=t.lastModified.getTime();!(o<i)&&t.sessionId&&n.push({cli:"opencode",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:o,sizeBytes:0})}}return n}async function tK(e){let t=await (0,tY.getOpenCodeSessionLog)(e.sessionId);return t?tR(t.entries,{cli:"opencode",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var tQ=e.i(19791),tV=e.i(85116);async function tX(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(await (0,tQ.getPiProjects)())){let{cwd:s,sessions:r}=await (0,tQ.getPiSessionsByEncodedName)(e.name),a=s??"";if(!t||t.has(a))for(let t of r){let s=t.lastModified.getTime();if(s<i)continue;let r=0;try{r=(0,o.statSync)(t.path).size}catch{}t.sessionId&&n.push({cli:"pi",projectName:e.name,sessionId:t.sessionId,transcriptPath:t.path,mtimeMs:s,sizeBytes:r})}}return n}async function t0(e){let t=await (0,tV.getPiSessionLog)(e.sessionId);return t?tR(t.entries,{cli:"pi",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var t1=e.i(64828),t3=e.i(28898),t8=e.i(3605);async function t9(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=await (0,t1.getHermesSessions)(),o=[];for(let e of n)!(e.mtimeMs<i)&&(!(e.messageCount<=0)||e.hasMessages)&&(!t||e.cwd&&t.has(e.cwd))&&o.push({cli:"hermes",projectName:e.cwd?(0,tI.encodeFolderName)(e.cwd):e.source?(0,t3.hermesProjectPath)(e.profile,e.source):`hermes:${e.profile}`,sessionId:e.sessionId,transcriptPath:`hermes://${e.sessionId}`,mtimeMs:e.mtimeMs,sizeBytes:e.messageCount});return o}async function t6(e){let t=await (0,t8.getHermesSessionLog)(e.sessionId);return t?tR(t.entries,{cli:"hermes",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var t2=e.i(90624),t4=e.i(64199);async function t5(e={}){if(e.projects&&e.projects.length>0)return[];let t=e.sinceMs??0,i=[];for(let e of(await (0,t2.getOpenClawSessions)()))e.mtimeMs<t||i.push({cli:"openclaw",projectName:(0,t2.openClawProjectPath)(e.agentId,e.channel),sessionId:e.sessionId,transcriptPath:e.transcriptPath,mtimeMs:e.mtimeMs,sizeBytes:e.sizeBytes});return i}async function t7(e){let t=await (0,t4.getOpenClawSessionLog)(e.sessionId);return t?tR(t.entries,{cli:"openclaw",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var ie=e.i(28246);async function it(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[];for(let e of(0,ie.listFactoryTranscripts)())!(e.mtimeMs<i)&&(!t||t.has(e.cwd))&&n.push({cli:"factory",projectName:e.projectName,sessionId:e.sessionId,transcriptPath:e.transcriptPath,mtimeMs:e.mtimeMs,sizeBytes:e.sizeBytes});return n}async function ii(e){let t;try{t=await (0,s.readFile)(e.transcriptPath,"utf-8")}catch{return[]}let i=(0,tx.parseRawLines)(t,"session"),n=(0,ie.factoryLinesToLogEntries)(i,"session"),o="";for(let e of i)if(e&&"object"==typeof e&&"session_start"===e.type){let t=e.cwd;if("string"==typeof t&&t.length>0){o=t;break}}return tR(n,{cli:"factory",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:o})}var io=e.i(93114),is=e.i(30441);async function ir(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=[],o=await (0,is.getAntigravityIndex)();for(let e of(0,io.listAntigravityTranscripts)()){if(e.mtimeMs<i)continue;let s=o.get(e.conversationId)?.cwd;(!t||s&&t.has(s))&&n.push({cli:"antigravity",projectName:s?(0,tI.encodeFolderName)(s):"antigravity",sessionId:e.conversationId,transcriptPath:e.transcriptPath,mtimeMs:e.mtimeMs,sizeBytes:e.sizeBytes})}return n}async function ia(e){let t;try{t=await (0,s.readFile)(e.transcriptPath,"utf-8")}catch{return[]}let i=(0,tx.parseRawLines)(t,"session"),n=(0,io.antigravityLinesToLogEntries)(i,"session"),o="";for(let e of i){if(!e||"object"!=typeof e)continue;let t=e.tool_calls;if(Array.isArray(t)){for(let e of t){let t=e&&"object"==typeof e?e.args:void 0,i=t&&"object"==typeof t?t.Cwd:void 0;if("string"==typeof i&&i.length>0){o=i;break}}if(o)break}}return tR(n,{cli:"antigravity",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:o})}var il=e.i(79364),ic=e.i(40375);async function id(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=await (0,il.getDevinSessions)(),o=[];for(let e of n)!(e.mtimeMs<i)&&(!t||e.cwd&&t.has(e.cwd))&&o.push({cli:"devin",projectName:e.projectName,sessionId:e.sessionId,transcriptPath:`devin-db://${e.sessionId}`,mtimeMs:e.mtimeMs,sizeBytes:0});return o}async function ip(e){let t=await (0,ic.getDevinSessionLog)(e.sessionId);return t?tR(t.entries,{cli:"devin",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}var iu=e.i(69164),im=e.i(36618);let ih={claude:{cli:"claude",listTranscripts:tO,streamEvents:t_},codex:{cli:"codex",listTranscripts:tD,streamEvents:tW},copilot:{cli:"copilot",listTranscripts:tz,streamEvents:tL},cursor:{cli:"cursor",listTranscripts:tH,streamEvents:tJ},opencode:{cli:"opencode",listTranscripts:tZ,streamEvents:tK},pi:{cli:"pi",listTranscripts:tX,streamEvents:t0},hermes:{cli:"hermes",listTranscripts:t9,streamEvents:t6},openclaw:{cli:"openclaw",listTranscripts:t5,streamEvents:t7},factory:{cli:"factory",listTranscripts:it,streamEvents:ii},devin:{cli:"devin",listTranscripts:id,streamEvents:ip},antigravity:{cli:"antigravity",listTranscripts:ir,streamEvents:ia},goose:{cli:"goose",listTranscripts:async function(e={}){let t=e.projects?new Set(e.projects):null,i=e.sinceMs??0,n=await (0,iu.getGooseSessions)(),o=[];for(let e of n)!(e.mtimeMs<i)&&(!t||e.cwd&&t.has(e.cwd))&&o.push({cli:"goose",projectName:e.projectName,sessionId:e.sessionId,transcriptPath:`goose-db://${e.sessionId}`,mtimeMs:e.mtimeMs,sizeBytes:0});return o},streamEvents:async function(e){let t=await (0,im.getGooseSessionLog)(e.sessionId);return t?tR(t.entries,{cli:"goose",sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:t.cwd??""}):[]}}},ig=/\.(?:ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|kt|swift|rb|php|c|h|cc|cpp|hpp|cs|scala|sh|bash|zsh|json|yaml|yml|toml|md|txt|sql|html|css|scss|sass)$/i,iy=["/","/home","/usr","/etc","/var","/opt","/Users"],ib="rereadAfterEdit",iw=[{name:"redundant-cd-cwd",description:"Bash commands prefixed with `cd <cwd> && …` even though commands already run in cwd.",category:"Wasteful",severity:"info",displayTitle:"Prepended cd <cwd> before commands",impact:"Pure waste — your agent's shell already runs in `cwd`.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;if("string"!=typeof t||!e.cwd)return null;let i=t.trimStart(),n=/^cd\s+(?:"([^"]+)"|'([^']+)'|(\S+))\s*&&\s*([\s\S]+)$/.exec(i);if(!n)return null;let o=(n[1]??n[2]??n[3]??"").replace(/\/+$/,"");if(o!==e.cwd.replace(/\/+$/,""))return null;let s=n[4].trim();return{example:`cd ${o} && ${s}`}}},{name:"prefer-edit-over-read-cat",description:"Bash `cat`/`head`/`tail`/`less`/`more` on a single source file — use Read.",category:"Wasteful",severity:"info",displayTitle:"Used `cat`/`head`/`tail` on a source file",impact:"Burns tokens; the Read tool returns content directly without going through Bash output.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;if("string"!=typeof t)return null;let i=t.trim();if(/[|<>;&`$()]/.test(i))return null;let n=/^(cat|head|tail|less|more)\s+(?:-\S+\s+)*(?:"([^"]+)"|'([^']+)'|(\S+))\s*$/.exec(i);if(!n)return null;let o=n[2]??n[3]??n[4]??"";return!o||/(?:^|\/)\.env(?:\..+)?$/.test(o)||!ig.test(o)?null:{example:i}}},{name:"prefer-edit-over-sed-awk",description:"Bash `sed -i`/`awk` in-place edits — use Edit.",category:"Wasteful",severity:"info",displayTitle:"Used sed -i or awk for an in-place edit",impact:"Edit tool is safer and produces a diff the agent can verify.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;if("string"!=typeof t)return null;let i=t.trim();return/(?:^|\s|;|&&|\|\|)sed\b[^|]*\s-i(?=\b|['"])/.test(i)||/(?:^|\s|;|&&|\|\|)awk\b[^|]*\s>\s*\S+/.test(i)&&!/\|/.test(i)?{example:i}:null}},{name:"prefer-write-over-heredoc",description:"Bash heredoc / `echo > file` writing multi-line content — use Write.",category:"Wasteful",severity:"info",displayTitle:"Used heredoc / `echo > file` to write a multi-line file",impact:"Write tool handles escaping and is verifiable.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;return"string"!=typeof t?null:/<<-?\s*['"]?[A-Za-z_][A-Za-z0-9_]*['"]?\s*>\s*\S/.test(t)||/(?:^|\s|;|&&|\|\|)(?:echo|printf)\s+["'][^"']*\n[^"']*["']\s*>\s*\S/.test(t)?{example:t.replace(/\s+/g," ").trim().slice(0,160)}:null}},{name:"sleep-polling-loop",description:"Bash long `sleep` or while-sleep polling loops.",category:"Wasteful",severity:"info",displayTitle:"Used a long sleep or while-sleep polling loop",impact:"Burns wall-clock; better to wait for an explicit signal.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;if("string"!=typeof t)return null;if(/\bwhile\b[\s\S]*?\bsleep\b[\s\S]*?\bdone\b/.test(t))return{example:t.replace(/\s+/g," ").trim().slice(0,160)};let i=/\bsleep\s+(\d+(?:\.\d+)?)(m|h|d)?\b/.exec(t);if(i){let e=parseFloat(i[1]),n=i[2]??"s";if(("m"===n?60*e:"h"===n?3600*e:"d"===n?86400*e:e)>=30)return{example:t.replace(/\s+/g," ").trim().slice(0,160)}}return null}},{name:"find-from-root",description:"Bash `find` against `/`, `/home`, `/usr`, etc. — scope to cwd instead.",category:"Risky",severity:"warn",displayTitle:"Ran find from /, /home, /usr, etc.",impact:"Filesystem-wide finds exhaust resources and rarely return useful results.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;if("string"!=typeof t)return null;let i=t.trim(),n=/(?:^|[\s;|&])find\s+(?:-\S+\s+)*("[^"]+"|'[^']+'|\S+)/.exec(i);if(!n)return null;let o=n[1].replace(/^["']|["']$/g,"").replace(/\/+$/,"")||"/";return iy.includes(o)?{example:i.slice(0,160)}:null}},{name:"git-commit-no-verify",description:"git commit invoked with --no-verify / -n, skipping hooks.",category:"Risky",severity:"warn",displayTitle:"Committed with --no-verify",impact:"Skips pre-commit hooks that exist to catch broken or unsafe code.",detect(e){if("Bash"!==e.toolName)return null;let t=e.toolInput.command;return"string"!=typeof t?null:/\bgit\s+commit\b/.test(t)&&(/\s--no-verify\b/.test(t)||/\s-n\b/.test(t))?{example:t.replace(/\s+/g," ").trim().slice(0,160)}:null}},{name:"reread-after-edit",description:"Read of a file that was just Edit'd or Write'n in the same session.",category:"Wasteful",severity:"info",displayTitle:"Re-read a file it just edited",impact:"Edit/Write already returned the updated content; the second Read is wasted tokens.",detect(e,t){let i,n=((i=t[ib])||(i={countdown:new Map},t[ib]=i),i),o=e.toolInput.file_path,s="string"==typeof o?o:null;for(let[e,t]of n.countdown)t<=1?n.countdown.delete(e):n.countdown.set(e,t-1);return s?"Edit"===e.toolName||"Write"===e.toolName?(n.countdown.set(s,5),null):"Read"===e.toolName&&n.countdown.has(s)?(n.countdown.delete(s),{example:`Read ${s} immediately after Edit/Write`}):null:null}}],ik=["cowboy","explorer","ghost","optimist","hammer","architect"],iv={explorer:.38,architect:.33,hammer:.11,cowboy:.11,optimist:.07,ghost:.01,precision:0,goldfish:0},iN={optimist:0,cowboy:0,explorer:0,goldfish:0,architect:0,precision:0,hammer:0,ghost:0};for(let e of ik)iN[e]=Math.max(iv[e],.05);var iS=e.i(66680);let iT=null,i$=null;function iP(){if(iT)return iT;let e=tl.map(e=>`${e.name}|${e.fn.toString()}`).sort().join("\n");return iT=(0,iS.createHash)("sha1").update(e).digest("hex").slice(0,16)}function iE(){if(i$)return i$;let e=iw.map(e=>`${e.name}|${e.detect.toString()}`).sort().join("\n");return i$=(0,iS.createHash)("sha1").update(e).digest("hex").slice(0,16)}function iC(e){let t=(0,b.auditCacheDir)(),i=(0,iS.createHash)("sha1").update(e).digest("hex");return(0,n.join)(t,`${i}.json`)}var iI=e.i(24214),iA=e.i(28067),ix=e.i(17694);let iR=iA.POSTHOG_API_KEY,iO=new Set;async function i_(e,t,i){let n=JSON.stringify({api_key:process.env.FAILPROOFAI_POSTHOG_KEY??iR,event:t,distinct_id:e,properties:{...i,$lib:"failproofai-hooks",failproofai_version:iI.version,product:iA.POSTHOG_PRODUCT}});try{await fetch(process.env.FAILPROOFAI_POSTHOG_HOST?`${process.env.FAILPROOFAI_POSTHOG_HOST}/capture/`:"https://us.i.posthog.com/capture/",{method:"POST",headers:{"Content-Type":"application/json"},body:n,signal:AbortSignal.timeout(5e3)})}catch{}}async function ij(e,t,i){if(!(0,ix.isTelemetryEnabled)())return;let n=i_(e,t,i);iO.add(n),n.finally(()=>iO.delete(n)),await n}var iB=e.i(10659);function iD(e,t){let i=e.trim(),n="string"==typeof t?t.trim():"";return n?i?`${i}. ${n}`:n:i}function iW(e,t){if(!e?.policyParams)return;let i=e.policyParams[t];if(i)return i;let n=`${f}/`;if(t.startsWith(n))return e.policyParams[t.slice(n.length)]}async function iM(e,t,i,n){let o=t.tool_name,s=t.tool_input,r=function(e,t){let i=globalThis[m];i||g(i=new Map);let n=`${e}:${t??""}`,o=i.get(n);if(o)return o;let s=y().filter(i=>(!i.match.events||!(i.match.events.length>0)||!!i.match.events.includes(e))&&(!i.match.toolNames||!(i.match.toolNames.length>0)||!!t&&!!i.match.toolNames.includes(t))).sort((e,t)=>t.priority-e.priority);return i.set(n,s),s}(e,o);if(C(`evaluating ${r.length} policies for ${e}`),0===r.length)return{exitCode:0,stdout:"",stderr:"",policyName:null,reason:null,decision:"allow"};let a={eventType:e,payload:t,toolName:o,toolInput:s,session:i,cli:i?.cli},l=[],c=[];for(let t of r){let o,s,r=t.params,d=iW(n,t.name)??{};if(r){let e={};for(let[t,i]of Object.entries(r))e[t]=t in d?d[t]:i.default;o={...a,params:e}}else o={...a,params:d};try{s=await t.fn(o)}catch(o){let n=o instanceof Error?o.message:String(o);I(`policy "${t.name}" threw: ${n}`),t.name.startsWith(`${f}/`)&&ij((0,iB.getInstanceId)(),"policy_evaluation_error",{policy_name:t.name,event_type:e,cli:i?.cli??null,error_type:o instanceof Error?o.name:"unknown"});continue}if("deny"===s.decision){let r,a=iD(s.reason??`Blocked by policy: ${t.name}`,iW(n,t.name)?.hint);C(`deny by "${t.name}": ${a}`),r=o.toolName?o.toolName:"UserPromptSubmit"===e?"prompt":"SessionStart"===e?"session start":"SessionEnd"===e?"session end":"Stop"===e?"stop":"operation";let l=`Blocked ${r} by failproofai because: ${a}, as per the policy configured by the user`;if(i?.cli==="cursor"){if("Stop"===e||"SubagentStop"===e)return{exitCode:0,stdout:JSON.stringify({followup_message:`MANDATORY ACTION REQUIRED from failproofai (policy: ${t.name}): ${a}
3
4
 
4
5
  You MUST complete the above action NOW. Do NOT ask the user for confirmation — execute the required action, then attempt to finish your task again.`}),stderr:"",policyName:t.name,reason:a,decision:"deny"};if("UserPromptSubmit"===e)return{exitCode:0,stdout:JSON.stringify({continue:!1,user_message:l}),stderr:"",policyName:t.name,reason:a,decision:"deny"};return{exitCode:0,stdout:JSON.stringify({permission:"deny",user_message:l,agent_message:l}),stderr:"",policyName:t.name,reason:a,decision:"deny"}}if(i?.cli==="pi"){if("Stop"===e)return{exitCode:0,stdout:JSON.stringify({permission:"deny",reason:`MANDATORY ACTION REQUIRED from failproofai (policy: ${t.name}): ${a}
5
6
 
@@ -13,9 +14,9 @@ You MUST complete the above action NOW. Do NOT ask the user for confirmation —
13
14
 
14
15
  You MUST complete the above action NOW. Do NOT ask the user for confirmation — execute the required action, then attempt to finish your task again.`:l}),stderr:"",policyName:t.name,reason:a,decision:"deny"};if(i?.cli==="antigravity"){if("Stop"===e)return{exitCode:0,stdout:JSON.stringify({decision:"continue",reason:`MANDATORY ACTION REQUIRED from failproofai (policy: ${t.name}): ${a}
15
16
 
16
- You MUST complete the above action NOW. Do NOT ask the user for confirmation — execute the required action, then attempt to finish your task again.`}),stderr:"",policyName:t.name,reason:a,decision:"deny"};return{exitCode:0,stdout:JSON.stringify({decision:"deny",reason:l}),stderr:"",policyName:t.name,reason:a,decision:"deny"}}if(i?.cli==="goose")return{exitCode:0,stdout:JSON.stringify({decision:"block",reason:l}),stderr:"",policyName:t.name,reason:a,decision:"deny"};if("PreToolUse"===e)return{exitCode:0,stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e,permissionDecision:"deny",permissionDecisionReason:l}}),stderr:"",policyName:t.name,reason:a,decision:"deny"};if(i?.cli==="copilot"){if("UserPromptSubmit"===e)return{exitCode:0,stdout:JSON.stringify({decision:"block",reason:l}),stderr:"",policyName:t.name,reason:a,decision:"deny"};if("PermissionRequest"===e)return{exitCode:0,stdout:JSON.stringify({behavior:"deny",message:l}),stderr:"",policyName:t.name,reason:a,decision:"deny"}}if("PermissionRequest"===e)return{exitCode:0,stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e,decision:{behavior:"deny",message:`Blocked ${s} by failproofai because: ${a}, as per the policy configured by the user`}}}),stderr:"",policyName:t.name,reason:a,decision:"deny"};if("PostToolUse"===e){if(i?.cli==="codex"||i?.cli==="copilot")return{exitCode:0,stdout:JSON.stringify({decision:"block",reason:l}),stderr:"",policyName:t.name,reason:a,decision:"deny"};return{exitCode:0,stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e,additionalContext:`Blocked ${s} by failproofai because: ${a}, as per the policy configured by the user`}}),stderr:"",policyName:t.name,reason:a,decision:"deny"}}if("Stop"===e||"SubagentStop"===e){let e=`MANDATORY ACTION REQUIRED from failproofai (policy: ${t.name}): ${a}
17
+ You MUST complete the above action NOW. Do NOT ask the user for confirmation — execute the required action, then attempt to finish your task again.`}),stderr:"",policyName:t.name,reason:a,decision:"deny"};return{exitCode:0,stdout:JSON.stringify({decision:"deny",reason:l}),stderr:"",policyName:t.name,reason:a,decision:"deny"}}if(i?.cli==="goose")return{exitCode:0,stdout:JSON.stringify({decision:"block",reason:l}),stderr:"",policyName:t.name,reason:a,decision:"deny"};if("PreToolUse"===e)return{exitCode:0,stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e,permissionDecision:"deny",permissionDecisionReason:l}}),stderr:"",policyName:t.name,reason:a,decision:"deny"};if(i?.cli==="copilot"){if("UserPromptSubmit"===e)return{exitCode:0,stdout:JSON.stringify({decision:"block",reason:l}),stderr:"",policyName:t.name,reason:a,decision:"deny"};if("PermissionRequest"===e)return{exitCode:0,stdout:JSON.stringify({behavior:"deny",message:l}),stderr:"",policyName:t.name,reason:a,decision:"deny"}}if("PermissionRequest"===e)return{exitCode:0,stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e,decision:{behavior:"deny",message:`Blocked ${r} by failproofai because: ${a}, as per the policy configured by the user`}}}),stderr:"",policyName:t.name,reason:a,decision:"deny"};if("PostToolUse"===e){if(i?.cli==="codex"||i?.cli==="copilot")return{exitCode:0,stdout:JSON.stringify({decision:"block",reason:l}),stderr:"",policyName:t.name,reason:a,decision:"deny"};return{exitCode:0,stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e,additionalContext:`Blocked ${r} by failproofai because: ${a}, as per the policy configured by the user`}}),stderr:"",policyName:t.name,reason:a,decision:"deny"}}if("Stop"===e||"SubagentStop"===e){let e=`MANDATORY ACTION REQUIRED from failproofai (policy: ${t.name}): ${a}
17
18
 
18
- You MUST complete the above action NOW. Do NOT ask the user for confirmation — execute the required action, then attempt to finish your task again.`;if(i?.cli==="copilot")return{exitCode:0,stdout:JSON.stringify({decision:"block",reason:e}),stderr:"",policyName:t.name,reason:a,decision:"deny"};return{exitCode:2,stdout:"",stderr:e,policyName:t.name,reason:a,decision:"deny"}}return{exitCode:2,stdout:"",stderr:a,policyName:t.name,reason:a,decision:"deny"}}if("instruct"===r.decision){let e=iA(r.reason??`Instruction from policy: ${t.name}`,iP(n,t.name)?.hint);l.push({policyName:t.name,reason:e}),(0,w.hookLogInfo)(`instruct by "${t.name}": ${e}`)}"allow"===r.decision&&r.reason&&c.push({policyName:t.name,reason:r.reason})}if(l.length>0){let t=l.map(e=>e.reason).join("\n"),n=l.map(e=>e.policyName);if(i?.cli==="cursor")return"Stop"===e||"SubagentStop"===e?{exitCode:0,stdout:JSON.stringify({followup_message:`Instruction from failproofai: ${t}`}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}:{exitCode:0,stdout:JSON.stringify({permission:"allow",additional_context:`Instruction from failproofai: ${t}`}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"};if(i?.cli==="pi"){if("Stop"===e){let e=1===n.length?`policy: ${n[0]}`:`policies: ${n.join(", ")}`;return{exitCode:0,stdout:JSON.stringify({permission:"deny",reason:`MANDATORY ACTION REQUIRED from failproofai (${e}): ${t}
19
+ You MUST complete the above action NOW. Do NOT ask the user for confirmation — execute the required action, then attempt to finish your task again.`;if(i?.cli==="copilot")return{exitCode:0,stdout:JSON.stringify({decision:"block",reason:e}),stderr:"",policyName:t.name,reason:a,decision:"deny"};return{exitCode:2,stdout:"",stderr:e,policyName:t.name,reason:a,decision:"deny"}}return{exitCode:2,stdout:"",stderr:a,policyName:t.name,reason:a,decision:"deny"}}if("instruct"===s.decision){let e=iD(s.reason??`Instruction from policy: ${t.name}`,iW(n,t.name)?.hint);l.push({policyName:t.name,reason:e}),C(`instruct by "${t.name}": ${e}`)}"allow"===s.decision&&s.reason&&c.push({policyName:t.name,reason:s.reason})}if(l.length>0){let t=l.map(e=>e.reason).join("\n"),n=l.map(e=>e.policyName);if(i?.cli==="cursor")return"Stop"===e||"SubagentStop"===e?{exitCode:0,stdout:JSON.stringify({followup_message:`Instruction from failproofai: ${t}`}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}:{exitCode:0,stdout:JSON.stringify({permission:"allow",additional_context:`Instruction from failproofai: ${t}`}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"};if(i?.cli==="pi"){if("Stop"===e){let e=1===n.length?`policy: ${n[0]}`:`policies: ${n.join(", ")}`;return{exitCode:0,stdout:JSON.stringify({permission:"deny",reason:`MANDATORY ACTION REQUIRED from failproofai (${e}): ${t}
19
20
 
20
21
  You MUST complete the above action(s) NOW. Do NOT ask the user for confirmation — execute the required action(s), then attempt to finish your task again.`}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}}return{exitCode:0,stdout:JSON.stringify({permission:"allow",reason:`Instruction from failproofai: ${t}`}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}}if(i?.cli==="hermes"){let e=l.map(e=>`[failproofai] ${e.policyName}: ${e.reason}`).join("\n");return{exitCode:0,stdout:JSON.stringify({decision:"allow",reason:`Instruction from failproofai: ${t}`}),stderr:e+"\n",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}}if(i?.cli==="openclaw"){if("Stop"===e){let e=1===n.length?`policy: ${n[0]}`:`policies: ${n.join(", ")}`;return{exitCode:0,stdout:JSON.stringify({permission:"deny",reason:`MANDATORY ACTION REQUIRED from failproofai (${e}): ${t}
21
22
 
@@ -29,6 +30,6 @@ You MUST complete the above action(s) NOW. Do NOT ask the user for confirmation
29
30
 
30
31
  You MUST complete the above action(s) NOW. Do NOT ask the user for confirmation — execute the required action(s), then attempt to finish your task again.`}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}}return{exitCode:0,stdout:"",stderr:l.map(e=>`[failproofai] ${e.policyName}: ${e.reason}`).join("\n")+"\n",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}}if(i?.cli==="goose")return{exitCode:0,stdout:"",stderr:l.map(e=>`[failproofai] ${e.policyName}: ${e.reason}`).join("\n")+"\n",policyName:n[0],policyNames:n,reason:t,decision:"instruct"};if("Stop"===e||"SubagentStop"===e){let e=1===n.length?`policy: ${n[0]}`:`policies: ${n.join(", ")}`,o=`MANDATORY ACTION REQUIRED from failproofai (${e}): ${t}
31
32
 
32
- You MUST complete the above action(s) NOW. Do NOT ask the user for confirmation — execute the required action(s), then attempt to finish your task again.`;return i?.cli==="copilot"?{exitCode:0,stdout:JSON.stringify({decision:"block",reason:o}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}:{exitCode:2,stdout:"",stderr:o,policyName:n[0],policyNames:n,reason:t,decision:"instruct"}}return{exitCode:0,stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e,additionalContext:`Instruction from failproofai: ${t}`}}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}}if(c.length>0){let t=c.map(e=>e.reason).join("\n"),n=c.map(e=>e.policyName);if(i?.cli==="cursor"){let e={permission:"allow",additional_context:`Note from failproofai: ${t}`},i=c.map(e=>`[failproofai] ${e.policyName}: ${e.reason}`).join("\n");return{exitCode:0,stdout:JSON.stringify(e),stderr:i+"\n",policyName:n[0],policyNames:n,reason:t,decision:"allow"}}if(i?.cli==="pi"){let e={permission:"allow",reason:`Note from failproofai: ${t}`},i=c.map(e=>`[failproofai] ${e.policyName}: ${e.reason}`).join("\n");return{exitCode:0,stdout:JSON.stringify(e),stderr:i+"\n",policyName:n[0],policyNames:n,reason:t,decision:"allow"}}if(i?.cli==="openclaw"){let e=c.map(e=>`[failproofai] ${e.policyName}: ${e.reason}`).join("\n");return{exitCode:0,stdout:JSON.stringify({permission:"allow",reason:`Note from failproofai: ${t}`}),stderr:e+"\n",policyName:n[0],policyNames:n,reason:t,decision:"allow"}}let o="PreToolUse"===e||"PostToolUse"===e||"UserPromptSubmit"===e||"PermissionRequest"===e,r=c.map(e=>`[failproofai] ${e.policyName}: ${e.reason}`).join("\n");return o?{exitCode:0,stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e,additionalContext:`Note from failproofai: ${t}`}}),stderr:r+"\n",policyName:n[0],policyNames:n,reason:t,decision:"allow"}:{exitCode:0,stdout:"",stderr:r+"\n",policyName:n[0],policyNames:n,reason:t,decision:"allow"}}return{exitCode:0,stdout:"",stderr:"",policyName:null,reason:null,decision:"allow"}}var ix=e.i(90521),iR=e.i(93119);let iO=new Set(["warn-repeated-tool-calls"].map(e=>h(e))),i_=!1,ij=null;async function iB(){if(i_)return;ij=[...y()],globalThis[u]=[],g(null);let e=e5.map(e=>e.name).filter(e=>!iO.has(h(e)));await iD(e)||function(e){let t=new Set(e.map(h));for(let e of e5)(e.alwaysOn||t.has(h(e.name)))&&b(e.name,e.description,e.fn,e.match,0,e.params)}(e),i_=!0}async function iD(e){let t,i=function(){let e=process.env.FAILPROOFAI_PACKAGE_ROOT;if(!e)return null;let t=(0,n.resolve)(e,"policy-pack");return(0,o.existsSync)((0,n.resolve)(t,"failproofai-pack.json"))?t:null}();if(!i)return!1;let r=(0,n.resolve)(i,"failproofai-pack.mjs");if(!(0,o.existsSync)(r))return!1;let s=new Set(e);try{(0,iR.clearCustomHooks)(),t=await (0,ix.loadCustomHooks)(r,{strict:!0})}catch{return!1}finally{(0,iR.clearCustomHooks)()}if(0===t.length)return!1;let a=new Map(t.map(e=>[e.name,e])),l=0;for(let e of e5){if(!s.has(e.name))continue;let t=a.get(e.name);if(e.alwaysOn||!t){b(e.name,e.description,e.fn,e.match,0,e.params);continue}b(t.name,t.description??e.description,t.fn,t.match??e.match,0,e.params),l+=1}return l>0}async function iW(e){i_||await iB();let t={sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:e.cwd,cli:e.cli},i={tool_name:e.toolName,tool_input:e.toolInput,session_id:e.sessionId,cwd:e.cwd,transcript_path:e.transcriptPath},n=[];if(iM(await iI("PreToolUse",i,t),"PreToolUse",n),void 0!==e.toolResultText){let o={...i,tool_response:e.toolResultText};iM(await iI("PostToolUse",o,t),"PostToolUse",n)}return n}function iM(e,t,i){for(let n of e.policyNames&&e.policyNames.length>0?e.policyNames:e.policyName?[e.policyName]:[])i.push({policyName:n,decision:e.decision,reason:e.reason,eventType:t})}function iU(e){let t=e.indexOf("/");return t>=0?e.slice(t+1):e}function iz(e){return e.length<=80?e:e.slice(0,79)+"…"}async function iL(e){let t={transcriptPath:e.transcriptPath,cli:e.cli,projectName:e.projectName,sessionId:e.sessionId,mtimeMs:e.mtimeMs,sizeBytes:e.sizeBytes,cwd:"",eventsScanned:0,hitsByName:{},examplesByName:{},rangeByName:{}},i=await io[e.cli].streamEvents(e);if(0===i.length)return t;t.eventsScanned=i.length,t.cwd=i[0].cwd||"";let n={};for(let e of i){let i;for(let i of il){let o=i.detect(e,n);o&&iF(t,i.name,e.timestamp,e.cwd,iz(o.example))}try{i=await iW(e)}catch{continue}for(let n of i){let i=function(e,t){if("Bash"===t.toolName){let e=t.toolInput.command;if("string"==typeof e)return e.replace(/\s+/g," ")}let i=t.toolInput.file_path;return"string"==typeof i?`${t.toolName} ${i}`:`${t.toolName}`}(n.policyName,e);iF(t,n.policyName,e.timestamp,e.cwd,iz(i))}}return t}function iF(e,t,i,n,o){e.hitsByName[t]=(e.hitsByName[t]??0)+1;let r=e.examplesByName[t]??[];r.length<3&&(r.push({timestamp:i,cwd:n,example:o}),e.examplesByName[t]=r);let s=e.rangeByName[t];s?(i<s.first&&(s.first=i),i>s.last&&(s.last=i)):e.rangeByName[t]={first:i,last:i}}async function iq(e={}){let t=Date.now();await iB();try{return await iH(e,t)}finally{if(i_){if(null!==ij){var i;i=ij,globalThis[u]=[...i],g(null),ij=null}i_=!1}}}async function iH(e,t){let n=e.clis??Array.from(te),r=function(e){if(!e)return;let t=/^(\d+)\s*([dhm])$/i.exec(e.trim());if(t){let e=parseInt(t[1],10),i=t[2].toLowerCase();return Date.now()-e*("d"===i?864e5:"h"===i?36e5:6e4)}let i=Date.parse(e);if(!Number.isNaN(i))return i;throw Error(`Invalid --since value: "${e}" (expected e.g. "7d", "30d", or "2026-04-01")`)}(e.since),s=new Set(((0,e7.readMergedHooksConfig)().enabledPolicies??[]).map(e=>h(e))),a=[];for(let t of n){let i,n=io[t];try{i=await n.listTranscripts({projects:e.projects,sinceMs:r})}catch{continue}a.push(...i)}let l=0,c=0,d=a.map(t=>async()=>{if(!e.noCache){let e=function(e,t,i){if(0===i)return null;let n=iT(e);if(!(0,o.existsSync)(n))return null;try{let e=(0,o.readFileSync)(n,"utf-8"),r=JSON.parse(e);if(3!==r.schemaVersion||r.mtimeMs!==t||r.sizeBytes!==i||r.engineVersion!==iS()||r.detectorVersion!==i$()||!Number.isFinite(r.cachedAt)||Date.now()-r.cachedAt>2592e6)return null;return r.result??null}catch{return null}}(t.transcriptPath,t.mtimeMs,t.sizeBytes);if(e)return e}try{let i=await iL(t);return e.noCache||function(e,t,i,n){if(0===i)return;let r=iT(e);try{(0,o.mkdirSync)((0,im.auditCacheDir)(),{recursive:!0});let e={schemaVersion:3,cachedAt:Date.now(),mtimeMs:t,sizeBytes:i,engineVersion:iS(),detectorVersion:i$(),result:n};(0,o.writeFileSync)(r,JSON.stringify(e),{encoding:"utf-8",mode:384});try{(0,o.chmodSync)(r,384)}catch{}}catch{}}(t.transcriptPath,t.mtimeMs,t.sizeBytes,i),i}catch{return c++,{transcriptPath:t.transcriptPath,cli:t.cli,projectName:t.projectName,cwd:"",sessionId:t.sessionId,mtimeMs:t.mtimeMs,sizeBytes:t.sizeBytes,eventsScanned:0,hitsByName:{},examplesByName:{},rangeByName:{}}}}),p=await (0,i.batchAll)(d,8),u=[];for(let e of p)"fulfilled"===e.status?u.push(e.value):l++;let m=function(e,t){let i=new Map;for(let t of e)for(let[e,n]of Object.entries(t.hitsByName)){let o=i.get(e)??{hits:0,projects:new Set,examples:[]};for(let i of(o.hits+=n,o.projects.add(t.projectName),t.examplesByName[e]??[]))o.examples.length<3&&o.examples.push({...i,sessionId:t.sessionId});let r=t.rangeByName[e];r&&((!o.first||r.first<o.first)&&(o.first=r.first),(!o.last||r.last>o.last)&&(o.last=r.last)),i.set(e,o)}let n=new Map(il.map(e=>[e.name,e])),o=[];for(let[e,r]of i){let i=n.get(e),s=!!i,a=s?null:function(e){let t=iU(e);for(let i of e5)if(i.name===e||iU(i.name)===t)return i;return null}(e),l=s?"audit-detector":"builtin",c=!s&&t.has(h(e)),d=i?.displayTitle??a?.displayTitle??i?.description??a?.description??iU(e),p=i?.impact??a?.impact??"";o.push({name:e,source:l,category:i?.category??a?.category??"Custom",severity:s?i?.severity??"info":function(e){let t,i=(t=e.indexOf("/"))>=0?e.slice(t+1):e;return i.startsWith("sanitize-")?"sanitize":i.startsWith("block-")?"deny":i.startsWith("warn-")||i.startsWith("protect-")||i.startsWith("prefer-")||i.startsWith("require-")?"warn":"deny"}(e),hits:r.hits,projects:r.projects.size,firstSeen:r.first,lastSeen:r.last,examples:r.examples,displayTitle:d,impact:p,enabledInConfig:c,installHint:"audit-detector"===l?"Audit-only — `failproofai audit` will keep tracking these.":c?"Already enforced — failproofai is blocking these in real time.":`Enable in one command: failproofai policies --install ${iU(e)}`})}return o.sort((e,t)=>t.hits-e.hits),o}(u,s);if(e.policies?.length){let t=new Set(e.policies.map(iU));m=m.filter(e=>t.has(iU(e.name)))}let f=m.reduce((e,t)=>e+t.hits,0),g=new Set,y=new Set,b=0;for(let e of u)Object.keys(e.hitsByName).length>0&&g.add(e.projectName),e.cwd&&y.add(e.cwd),b+=e.eventsScanned??0;return{version:2,scannedAt:new Date(t).toISOString(),scope:{cli:n,projects:e.projects??"all",since:e.since??null},transcripts:{scanned:a.length,skipped:l,errors:c,durationMs:Date.now()-t},results:m,totals:{hits:f,projectsWithHits:g.size},projectsScanned:[...y].sort(),eventsScanned:b,enabledBuiltinNames:[...s].map(e=>e.includes("/")?e.slice(e.indexOf("/")+1):e)}}var iJ=e.i(47756),iG=e.i(48480),iZ=e.i(29095),iY=e.i(46501);let iK=new Set(te);async function iQ(e){await (0,iY.initTelemetry)();let i={};try{let n=await e.text();if(n.trim().length>0){let e=JSON.parse(n);if(null===e||"object"!=typeof e||Array.isArray(e))return(0,iY.trackEvent)("audit_run_rejected",{source:"dashboard",reason:"non_object_body"}),t.NextResponse.json({error:"Request body must be a JSON object"},{status:400});i=e}}catch{return(0,iY.trackEvent)("audit_run_rejected",{source:"dashboard",reason:"invalid_json"}),t.NextResponse.json({error:"Invalid JSON body"},{status:400})}let n=function(e){let t={};if("string"==typeof e.since&&e.since.trim()&&(t.since=e.since.trim()),Array.isArray(e.cli)&&e.cli.length>0){let i=e.cli.filter(e=>"string"==typeof e&&iK.has(e));i.length>0&&(t.clis=i)}return Array.isArray(e.project)&&e.project.length>0&&(t.projects=e.project.filter(e=>"string"==typeof e)),Array.isArray(e.policy)&&e.policy.length>0&&(t.policies=e.policy.filter(e=>"string"==typeof e)),!0===e.noCache&&(t.noCache=!0),t}(i);if(!(0,iG.tryAcquireRun)())return(0,iY.trackEvent)("audit_run_rejected",{source:"dashboard",reason:"already_running"}),t.NextResponse.json({error:"Audit already running",status:"already-running"},{status:409});let o=(0,iZ.acquireAuditLock)("dashboard");if(!o.ok)return(0,iG.finishRun)(null),(0,iY.trackEvent)("audit_run_rejected",{source:"dashboard",reason:"cross_process_lock"}),t.NextResponse.json({error:"Audit already running",status:"already-running"},{status:409});(0,iY.trackEvent)("audit_run_started",{source:"dashboard",since:n.since??null,no_cache:!0===n.noCache,cli_count:n.clis?.length??0,project_count:n.projects?.length??0});let r=Date.now();return(async()=>{try{let e=await iq(n),t=(0,iJ.writeDashboardCache)(n,e);(0,iY.trackEvent)("audit_run_completed",{source:"dashboard",duration_ms:Date.now()-r,events_scanned:e.eventsScanned,sessions_scanned:e.transcripts.scanned,projects_scanned:e.projectsScanned.length,findings:e.results.length,total_hits:e.totals.hits,persisted:t}),(0,iG.finishRun)(t?null:"audit finished but its result could not be saved")}catch(e){(0,iY.trackEvent)("audit_run_failed",{source:"dashboard",duration_ms:Date.now()-r,error_type:e instanceof Error?e.name:"unknown",error_message:function(e){let t;try{t=e instanceof Error?e.message:String(e)}catch{return"unknown"}if(!t)return"";let i="";try{i=a.default.homedir()}catch{}return i&&i.length>1&&(t=t.split(i).join("~")),t.length>300&&(t=t.slice(0,300)+"…"),t}(e)}),(0,iG.finishRun)(e instanceof Error?e.message:String(e))}finally{o.lock.release()}})(),t.NextResponse.json({status:"started"},{status:202})}e.s(["POST",0,iQ,"dynamic",0,"force-dynamic"],97610)},89498,e=>{"use strict";var t=e.i(47909),i=e.i(74017),n=e.i(96250),o=e.i(59756),r=e.i(61916),s=e.i(74677),a=e.i(69741),l=e.i(16795),c=e.i(87718),d=e.i(95169),p=e.i(47587),u=e.i(66012),m=e.i(70101),f=e.i(26937),h=e.i(10372),g=e.i(93695);e.i(52474);var y=e.i(220);let b=new t.AppRouteRouteModule({definition:{kind:i.RouteKind.APP_ROUTE,page:"/api/audit/run/route",pathname:"/api/audit/run",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/app/api/audit/run/route.ts",nextConfigOutput:"standalone",userland:()=>e.r(97610),...{}}),{workAsyncStorage:w,workUnitAsyncStorage:k,serverHooks:v}=b;async function N(e,t,n){n.requestMeta&&(0,o.setRequestMeta)(e,n.requestMeta),b.isDev&&(0,o.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let w="/api/audit/run/route";w=w.replace(/\/index$/,"")||"/";let k=await b.prepare(e,t,{srcPage:w,multiZoneDraftMode:!1});if(!k)return t.statusCode=400,t.end("Bad Request"),null==n.waitUntil||n.waitUntil.call(n,Promise.resolve()),null;let{buildId:v,deploymentId:N,params:S,nextConfig:$,parsedUrl:T,isDraftMode:E,prerenderManifest:C,routerServerContext:A,isOnDemandRevalidate:P,revalidateOnlyGenerated:I,resolvedPathname:x,clientReferenceManifest:R,serverActionsManifest:O}=k,_=(0,a.normalizeAppPath)(w),j=!!(C.dynamicRoutes[_]||C.routes[x]),B=async()=>((null==A?void 0:A.render404)?await A.render404(e,t,T,!1):t.end("This page could not be found"),null);if(j&&!E){let e=!!C.routes[x],t=C.dynamicRoutes[_];if(t&&!1===t.fallback&&!e){if($.adapterPath)return await B();throw new g.NoFallbackError}}let D=null;!j||b.isDev||E||(D="/index"===(D=x)?"/":D);let W=!0===b.isDev||!j,M=j&&!W;O&&R&&(0,s.setManifestsSingleton)({page:w,clientReferenceManifest:R,serverActionsManifest:O});let U=e.method||"GET",z=(0,r.getTracer)(),L=z.getActiveScopeSpan(),F=!!(null==A?void 0:A.isWrappedByNextServer),q=!!(0,o.getRequestMeta)(e,"minimalMode"),H=(0,o.getRequestMeta)(e,"incrementalCache")||await b.getIncrementalCache(e,$,C,q);null==H||H.resetRequestCache(),globalThis.__incrementalCache=H;let J={params:S,previewProps:C.preview,renderOpts:{experimental:{authInterrupts:!!$.experimental.authInterrupts,useCacheTimeout:$.experimental.useCacheTimeout},cacheComponents:!!$.cacheComponents,validationLevel:$.experimental.instantInsights.validationLevel,supportsDynamicResponse:W,incrementalCache:H,hmrRefreshHash:(0,o.getRequestMeta)(e,"hmrRefreshHash"),cacheLifeProfiles:$.cacheLife,staticPageGenerationTimeout:$.staticPageGenerationTimeout,waitUntil:n.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,i,n,o)=>b.onRequestError(e,t,n,o,A)},sharedContext:{buildId:v,deploymentId:N}},G=new l.NodeNextRequest(e),Z=new l.NodeNextResponse(t),Y=c.NextRequestAdapter.fromNodeNextRequest(G,(0,c.signalFromNodeResponse)(t)),K=async({previousCacheEntry:i})=>{try{if(!q&&P&&I&&!i)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let o=await b.handle(Y,J);e.fetchMetrics=J.renderOpts.fetchMetrics;let r=J.renderOpts.pendingWaitUntil;r&&n.waitUntil&&(n.waitUntil(r),r=void 0);let s=J.renderOpts.collectedTags;if(!j)return await (0,u.sendResponse)(G,Z,o,r),null;{let e=await o.blob(),t=(0,m.toNodeOutgoingHttpHeaders)(o.headers);s&&(t[h.NEXT_CACHE_TAGS_HEADER]=s),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let i=void 0!==J.renderOpts.collectedRevalidate&&!(J.renderOpts.collectedRevalidate>=h.INFINITE_CACHE)&&J.renderOpts.collectedRevalidate,n=void 0===J.renderOpts.collectedExpire||J.renderOpts.collectedExpire>=h.INFINITE_CACHE?!1!==i&&i>0?$.expireTime:void 0:J.renderOpts.collectedExpire;return{value:{kind:y.CachedRouteKind.APP_ROUTE,status:o.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:i,expire:n}}}}catch(t){throw(null==i?void 0:i.isStale)&&await b.onRequestError(e,t,{routerKind:"App Router",routePath:w,routeType:"route",revalidateReason:(0,p.getRevalidateReason)({isStaticGeneration:M,isOnDemandRevalidate:P})},!1,A),t}},Q=async(o,s)=>{try{var a,l;let o=await b.handleResponse({req:e,nextConfig:$,cacheKey:D,routeKind:i.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:C,isRoutePPREnabled:!1,isOnDemandRevalidate:P,revalidateOnlyGenerated:I,responseGenerator:K,waitUntil:n.waitUntil,isMinimalMode:q});if(!j)return;if((null==o||null==(a=o.value)?void 0:a.kind)!==y.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==o||null==(l=o.value)?void 0:l.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});q||t.setHeader("x-nextjs-cache",P?"REVALIDATED":o.isMiss?"MISS":o.isStale?"STALE":"HIT"),E&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let r=(0,m.fromNodeOutgoingHttpHeaders)(o.value.headers);q&&j||r.delete(h.NEXT_CACHE_TAGS_HEADER),!o.cacheControl||t.getHeader("Cache-Control")||r.get("Cache-Control")||r.set("Cache-Control",(0,f.getCacheControlHeader)(o.cacheControl)),await (0,u.sendResponse)(G,Z,new Response(o.value.body,{headers:r,status:o.value.status||200}));return}catch(t){if(t instanceof g.NoFallbackError||await b.onRequestError(e,t,{routerKind:"App Router",routePath:_,routeType:"route",revalidateReason:(0,p.getRevalidateReason)({isStaticGeneration:M,isOnDemandRevalidate:P})},!1,A),j)throw t;await (0,u.sendResponse)(G,Z,new Response(null,{status:500}));return}finally{(()=>{if(!o)return;let e=t.statusCode;o.setAttributes({"http.status_code":e,"next.rsc":!1}),e&&e>=500&&(o.setStatus({code:r.SpanStatusCode.ERROR}),o.setAttribute("error.type",e.toString()));let i=z.getRootSpanAttributes();if(!i)return;if(i.get("next.span_type")!==d.BaseServerSpan.handleRequest)return console.warn(`Unexpected root span type '${i.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let n=i.get("next.route")||_,a=`${U} ${n}`;o.setAttributes({"next.route":n,"http.route":n,"next.span_name":a}),o.updateName(a),s&&s!==o&&(s.setAttribute("http.route",n),s.updateName(a))})()}};if(F&&L)await Q(L,void 0);else{let t=z.getActiveScopeSpan();await z.withPropagatedContext(e.headers,()=>z.trace(d.BaseServerSpan.handleRequest,{spanName:`${U} ${w}`,kind:r.SpanKind.SERVER,attributes:{"http.method":U,"http.target":e.url}},e=>Q(e,t)),void 0,!F)}}e.s(["handler",0,N,"patchFetch",0,function(){return(0,n.patchFetch)({workAsyncStorage:w,workUnitAsyncStorage:k})},"routeModule",0,b,"serverHooks",0,v,"workAsyncStorage",0,w,"workUnitAsyncStorage",0,k])}];
33
+ You MUST complete the above action(s) NOW. Do NOT ask the user for confirmation — execute the required action(s), then attempt to finish your task again.`;return i?.cli==="copilot"?{exitCode:0,stdout:JSON.stringify({decision:"block",reason:o}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}:{exitCode:2,stdout:"",stderr:o,policyName:n[0],policyNames:n,reason:t,decision:"instruct"}}return{exitCode:0,stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e,additionalContext:`Instruction from failproofai: ${t}`}}),stderr:"",policyName:n[0],policyNames:n,reason:t,decision:"instruct"}}if(c.length>0){let t=c.map(e=>e.reason).join("\n"),n=c.map(e=>e.policyName);if(i?.cli==="cursor"){let e={permission:"allow",additional_context:`Note from failproofai: ${t}`},i=c.map(e=>`[failproofai] ${e.policyName}: ${e.reason}`).join("\n");return{exitCode:0,stdout:JSON.stringify(e),stderr:i+"\n",policyName:n[0],policyNames:n,reason:t,decision:"allow"}}if(i?.cli==="pi"){let e={permission:"allow",reason:`Note from failproofai: ${t}`},i=c.map(e=>`[failproofai] ${e.policyName}: ${e.reason}`).join("\n");return{exitCode:0,stdout:JSON.stringify(e),stderr:i+"\n",policyName:n[0],policyNames:n,reason:t,decision:"allow"}}if(i?.cli==="openclaw"){let e=c.map(e=>`[failproofai] ${e.policyName}: ${e.reason}`).join("\n");return{exitCode:0,stdout:JSON.stringify({permission:"allow",reason:`Note from failproofai: ${t}`}),stderr:e+"\n",policyName:n[0],policyNames:n,reason:t,decision:"allow"}}let o="PreToolUse"===e||"PostToolUse"===e||"UserPromptSubmit"===e||"PermissionRequest"===e,s=c.map(e=>`[failproofai] ${e.policyName}: ${e.reason}`).join("\n");return o?{exitCode:0,stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e,additionalContext:`Note from failproofai: ${t}`}}),stderr:s+"\n",policyName:n[0],policyNames:n,reason:t,decision:"allow"}:{exitCode:0,stdout:"",stderr:s+"\n",policyName:n[0],policyNames:n,reason:t,decision:"allow"}}return{exitCode:0,stdout:"",stderr:"",policyName:null,reason:null,decision:"allow"}}let iU=new Set(["warn-repeated-tool-calls"].map(e=>h(e))),iz=!1,iL=null;async function iF(){if(iz)return;iL=[...y()],globalThis[u]=[],g(null);let e=new Set(tl.map(e=>e.name).filter(e=>!iU.has(h(e))).map(h));for(let t of tl)(t.alwaysOn||e.has(h(t.name)))&&function(e,t,i,n,o=0,s){let r=h(e),a=y(),l=a.findIndex(e=>e.name===r),c={name:r,description:t,fn:i,match:n,priority:o,...s?{params:s}:{}};l>=0?a[l]=c:a.push(c),g(null)}(t.name,t.description,t.fn,t.match,0,t.params);iz=!0}async function iq(e){iz||await iF();let t={sessionId:e.sessionId,transcriptPath:e.transcriptPath,cwd:e.cwd,cli:e.cli},i={tool_name:e.toolName,tool_input:e.toolInput,session_id:e.sessionId,cwd:e.cwd,transcript_path:e.transcriptPath},n=[];if(iH(await iM("PreToolUse",i,t),"PreToolUse",n),void 0!==e.toolResultText){let o={...i,tool_response:e.toolResultText};iH(await iM("PostToolUse",o,t),"PostToolUse",n)}return n}function iH(e,t,i){for(let n of e.policyNames&&e.policyNames.length>0?e.policyNames:e.policyName?[e.policyName]:[])i.push({policyName:n,decision:e.decision,reason:e.reason,eventType:t})}function iJ(e){let t=e.indexOf("/");return t>=0?e.slice(t+1):e}function iG(e){return e.length<=80?e:e.slice(0,79)+"…"}async function iY(e){let t={transcriptPath:e.transcriptPath,cli:e.cli,projectName:e.projectName,sessionId:e.sessionId,mtimeMs:e.mtimeMs,sizeBytes:e.sizeBytes,cwd:"",eventsScanned:0,hitsByName:{},examplesByName:{},rangeByName:{}},i=await ih[e.cli].streamEvents(e);if(0===i.length)return t;t.eventsScanned=i.length,t.cwd=i[0].cwd||"";let n={};for(let e of i){let i;for(let i of iw){let o=i.detect(e,n);o&&iZ(t,i.name,e.timestamp,e.cwd,iG(o.example))}try{i=await iq(e)}catch{continue}for(let n of i){let i=function(e,t){if("Bash"===t.toolName){let e=t.toolInput.command;if("string"==typeof e)return e.replace(/\s+/g," ")}let i=t.toolInput.file_path;return"string"==typeof i?`${t.toolName} ${i}`:`${t.toolName}`}(n.policyName,e);iZ(t,n.policyName,e.timestamp,e.cwd,iG(i))}}return t}function iZ(e,t,i,n,o){e.hitsByName[t]=(e.hitsByName[t]??0)+1;let s=e.examplesByName[t]??[];s.length<3&&(s.push({timestamp:i,cwd:n,example:o}),e.examplesByName[t]=s);let r=e.rangeByName[t];r?(i<r.first&&(r.first=i),i>r.last&&(r.last=i)):e.rangeByName[t]={first:i,last:i}}async function iK(e={}){let t=Date.now();await iF();try{return await iQ(e,t)}finally{if(iz){if(null!==iL){var i;i=iL,globalThis[u]=[...i],g(null),iL=null}iz=!1}}}async function iQ(e,t){let s=e.clis??Array.from(td),r=function(e){if(!e)return;let t=/^(\d+)\s*([dhm])$/i.exec(e.trim());if(t){let e=parseInt(t[1],10),i=t[2].toLowerCase();return Date.now()-e*("d"===i?864e5:"h"===i?36e5:6e4)}let i=Date.parse(e);if(!Number.isNaN(i))return i;throw Error(`Invalid --since value: "${e}" (expected e.g. "7d", "30d", or "2026-04-01")`)}(e.since),l=new Set(((function(){let e=function(e){let t=(0,a.homedir)(),i=(0,n.resolve)(e);for(;i!==t;){let e=(0,n.resolve)(i,".failproofai");try{if((0,o.statSync)(e).isDirectory())return i}catch{}let t=(0,n.dirname)(i);if(t===i)break;i=t}return(0,n.resolve)(e)}((void 0)??process.cwd()),t=(0,n.resolve)(e,".failproofai","policies-config.json"),i=(0,n.resolve)(e,".failproofai","policies-config.local.json"),s=(0,b.globalPolicyConfigFile)(),r=tc(t),l=tc(i),c=tc(s),d=new Set([...r.enabledPolicies??[],...l.enabledPolicies??[],...c.enabledPolicies??[]]),p={};for(let e of[r,l,c])if(e.policyParams)for(let[t,i]of Object.entries(e.policyParams))t in p||(p[t]=i);let u=[r,l,c].map(e=>void 0!==e.customPoliciesPaths?e.customPoliciesPaths:void 0!==e.customPoliciesPath?[e.customPoliciesPath]:void 0).find(e=>void 0!==e),m=new Set([...r.disabledCustomPolicies??[],...l.disabledCustomPolicies??[],...c.disabledCustomPolicies??[]]),f=r.customPoliciesEnabled??l.customPoliciesEnabled??c.customPoliciesEnabled,h=r.llm??l.llm??c.llm;return{enabledPolicies:[...d],...Object.keys(p).length>0?{policyParams:p}:{},...void 0!==u?{customPoliciesPaths:u}:{},...m.size?{disabledCustomPolicies:[...m]}:{},...void 0!==f?{customPoliciesEnabled:f}:{},...void 0!==h?{llm:h}:{}}})().enabledPolicies??[]).map(e=>h(e))),c=[];for(let t of s){let i,n=ih[t];try{i=await n.listTranscripts({projects:e.projects,sinceMs:r})}catch{continue}c.push(...i)}let d=0,p=0,u=c.map(t=>async()=>{if(!e.noCache){let e=function(e,t,i){if(0===i)return null;let n=iC(e);if(!(0,o.existsSync)(n))return null;try{let e=(0,o.readFileSync)(n,"utf-8"),s=JSON.parse(e);if(3!==s.schemaVersion||s.mtimeMs!==t||s.sizeBytes!==i||s.engineVersion!==iP()||s.detectorVersion!==iE()||!Number.isFinite(s.cachedAt)||Date.now()-s.cachedAt>2592e6)return null;return s.result??null}catch{return null}}(t.transcriptPath,t.mtimeMs,t.sizeBytes);if(e)return e}try{let i=await iY(t);return e.noCache||function(e,t,i,n){if(0===i)return;let s=iC(e);try{(0,o.mkdirSync)((0,b.auditCacheDir)(),{recursive:!0});let e={schemaVersion:3,cachedAt:Date.now(),mtimeMs:t,sizeBytes:i,engineVersion:iP(),detectorVersion:iE(),result:n};(0,o.writeFileSync)(s,JSON.stringify(e),{encoding:"utf-8",mode:384});try{(0,o.chmodSync)(s,384)}catch{}}catch{}}(t.transcriptPath,t.mtimeMs,t.sizeBytes,i),i}catch{return p++,{transcriptPath:t.transcriptPath,cli:t.cli,projectName:t.projectName,cwd:"",sessionId:t.sessionId,mtimeMs:t.mtimeMs,sizeBytes:t.sizeBytes,eventsScanned:0,hitsByName:{},examplesByName:{},rangeByName:{}}}}),m=await (0,i.batchAll)(u,8),f=[];for(let e of m)"fulfilled"===e.status?f.push(e.value):d++;let g=function(e,t){let i=new Map;for(let t of e)for(let[e,n]of Object.entries(t.hitsByName)){let o=i.get(e)??{hits:0,projects:new Set,examples:[]};for(let i of(o.hits+=n,o.projects.add(t.projectName),t.examplesByName[e]??[]))o.examples.length<3&&o.examples.push({...i,sessionId:t.sessionId});let s=t.rangeByName[e];s&&((!o.first||s.first<o.first)&&(o.first=s.first),(!o.last||s.last>o.last)&&(o.last=s.last)),i.set(e,o)}let n=new Map(iw.map(e=>[e.name,e])),o=[];for(let[e,s]of i){let i=n.get(e),r=!!i,a=r?null:function(e){let t=iJ(e);for(let i of tl)if(i.name===e||iJ(i.name)===t)return i;return null}(e),l=r?"audit-detector":"builtin",c=!r&&t.has(h(e)),d=i?.displayTitle??a?.displayTitle??i?.description??a?.description??iJ(e),p=i?.impact??a?.impact??"";o.push({name:e,source:l,category:i?.category??a?.category??"Custom",severity:r?i?.severity??"info":function(e){let t,i=(t=e.indexOf("/"))>=0?e.slice(t+1):e;return i.startsWith("sanitize-")?"sanitize":i.startsWith("block-")?"deny":i.startsWith("warn-")||i.startsWith("protect-")||i.startsWith("prefer-")||i.startsWith("require-")?"warn":"deny"}(e),hits:s.hits,projects:s.projects.size,firstSeen:s.first,lastSeen:s.last,examples:s.examples,displayTitle:d,impact:p,enabledInConfig:c,installHint:"audit-detector"===l?"Audit-only — `failproofai audit` will keep tracking these.":c?"Already enforced — failproofai is blocking these in real time.":`Enable in one command: failproofai policies --install ${iJ(e)}`})}return o.sort((e,t)=>t.hits-e.hits),o}(f,l);if(e.policies?.length){let t=new Set(e.policies.map(iJ));g=g.filter(e=>t.has(iJ(e.name)))}let y=g.reduce((e,t)=>e+t.hits,0),w=new Set,k=new Set,v=0;for(let e of f)Object.keys(e.hitsByName).length>0&&w.add(e.projectName),e.cwd&&k.add(e.cwd),v+=e.eventsScanned??0;return{version:2,scannedAt:new Date(t).toISOString(),scope:{cli:s,projects:e.projects??"all",since:e.since??null},transcripts:{scanned:c.length,skipped:d,errors:p,durationMs:Date.now()-t},results:g,totals:{hits:y,projectsWithHits:w.size},projectsScanned:[...k].sort(),eventsScanned:v,enabledBuiltinNames:[...l].map(e=>e.includes("/")?e.slice(e.indexOf("/")+1):e)}}var iV=e.i(47756),iX=e.i(48480),i0=e.i(29095),i1=e.i(46501);let i3=new Set(td);async function i8(e){await (0,i1.initTelemetry)();let i={};try{let n=await e.text();if(n.trim().length>0){let e=JSON.parse(n);if(null===e||"object"!=typeof e||Array.isArray(e))return(0,i1.trackEvent)("audit_run_rejected",{source:"dashboard",reason:"non_object_body"}),t.NextResponse.json({error:"Request body must be a JSON object"},{status:400});i=e}}catch{return(0,i1.trackEvent)("audit_run_rejected",{source:"dashboard",reason:"invalid_json"}),t.NextResponse.json({error:"Invalid JSON body"},{status:400})}let n=function(e){let t={};if("string"==typeof e.since&&e.since.trim()&&(t.since=e.since.trim()),Array.isArray(e.cli)&&e.cli.length>0){let i=e.cli.filter(e=>"string"==typeof e&&i3.has(e));i.length>0&&(t.clis=i)}return Array.isArray(e.project)&&e.project.length>0&&(t.projects=e.project.filter(e=>"string"==typeof e)),Array.isArray(e.policy)&&e.policy.length>0&&(t.policies=e.policy.filter(e=>"string"==typeof e)),!0===e.noCache&&(t.noCache=!0),t}(i);if(!(0,iX.tryAcquireRun)())return(0,i1.trackEvent)("audit_run_rejected",{source:"dashboard",reason:"already_running"}),t.NextResponse.json({error:"Audit already running",status:"already-running"},{status:409});let o=(0,i0.acquireAuditLock)("dashboard");if(!o.ok)return(0,iX.finishRun)(null),(0,i1.trackEvent)("audit_run_rejected",{source:"dashboard",reason:"cross_process_lock"}),t.NextResponse.json({error:"Audit already running",status:"already-running"},{status:409});(0,i1.trackEvent)("audit_run_started",{source:"dashboard",since:n.since??null,no_cache:!0===n.noCache,cli_count:n.clis?.length??0,project_count:n.projects?.length??0});let s=Date.now();return(async()=>{try{let e=await iK(n),t=(0,iV.writeDashboardCache)(n,e);(0,i1.trackEvent)("audit_run_completed",{source:"dashboard",duration_ms:Date.now()-s,events_scanned:e.eventsScanned,sessions_scanned:e.transcripts.scanned,projects_scanned:e.projectsScanned.length,findings:e.results.length,total_hits:e.totals.hits,persisted:t}),(0,iX.finishRun)(t?null:"audit finished but its result could not be saved")}catch(e){(0,i1.trackEvent)("audit_run_failed",{source:"dashboard",duration_ms:Date.now()-s,error_type:e instanceof Error?e.name:"unknown",error_message:function(e){let t;try{t=e instanceof Error?e.message:String(e)}catch{return"unknown"}if(!t)return"";let i="";try{i=a.default.homedir()}catch{}return i&&i.length>1&&(t=t.split(i).join("~")),t.length>300&&(t=t.slice(0,300)+"…"),t}(e)}),(0,iX.finishRun)(e instanceof Error?e.message:String(e))}finally{o.lock.release()}})(),t.NextResponse.json({status:"started"},{status:202})}e.s(["POST",0,i8,"dynamic",0,"force-dynamic"],97610)},89498,e=>{"use strict";var t=e.i(47909),i=e.i(74017),n=e.i(96250),o=e.i(59756),s=e.i(61916),r=e.i(74677),a=e.i(69741),l=e.i(16795),c=e.i(87718),d=e.i(95169),p=e.i(47587),u=e.i(66012),m=e.i(70101),f=e.i(26937),h=e.i(10372),g=e.i(93695);e.i(52474);var y=e.i(220);let b=new t.AppRouteRouteModule({definition:{kind:i.RouteKind.APP_ROUTE,page:"/api/audit/run/route",pathname:"/api/audit/run",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/app/api/audit/run/route.ts",nextConfigOutput:"standalone",userland:()=>e.r(97610),...{}}),{workAsyncStorage:w,workUnitAsyncStorage:k,serverHooks:v}=b;async function N(e,t,n){n.requestMeta&&(0,o.setRequestMeta)(e,n.requestMeta),b.isDev&&(0,o.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let w="/api/audit/run/route";w=w.replace(/\/index$/,"")||"/";let k=await b.prepare(e,t,{srcPage:w,multiZoneDraftMode:!1});if(!k)return t.statusCode=400,t.end("Bad Request"),null==n.waitUntil||n.waitUntil.call(n,Promise.resolve()),null;let{buildId:v,deploymentId:N,params:S,nextConfig:T,parsedUrl:$,isDraftMode:P,prerenderManifest:E,routerServerContext:C,isOnDemandRevalidate:I,revalidateOnlyGenerated:A,resolvedPathname:x,clientReferenceManifest:R,serverActionsManifest:O}=k,_=(0,a.normalizeAppPath)(w),j=!!(E.dynamicRoutes[_]||E.routes[x]),B=async()=>((null==C?void 0:C.render404)?await C.render404(e,t,$,!1):t.end("This page could not be found"),null);if(j&&!P){let e=!!E.routes[x],t=E.dynamicRoutes[_];if(t&&!1===t.fallback&&!e){if(T.adapterPath)return await B();throw new g.NoFallbackError}}let D=null;!j||b.isDev||P||(D="/index"===(D=x)?"/":D);let W=!0===b.isDev||!j,M=j&&!W;O&&R&&(0,r.setManifestsSingleton)({page:w,clientReferenceManifest:R,serverActionsManifest:O});let U=e.method||"GET",z=(0,s.getTracer)(),L=z.getActiveScopeSpan(),F=!!(null==C?void 0:C.isWrappedByNextServer),q=!!(0,o.getRequestMeta)(e,"minimalMode"),H=(0,o.getRequestMeta)(e,"incrementalCache")||await b.getIncrementalCache(e,T,E,q);null==H||H.resetRequestCache(),globalThis.__incrementalCache=H;let J={params:S,previewProps:E.preview,renderOpts:{experimental:{authInterrupts:!!T.experimental.authInterrupts,useCacheTimeout:T.experimental.useCacheTimeout},cacheComponents:!!T.cacheComponents,validationLevel:T.experimental.instantInsights.validationLevel,supportsDynamicResponse:W,incrementalCache:H,hmrRefreshHash:(0,o.getRequestMeta)(e,"hmrRefreshHash"),cacheLifeProfiles:T.cacheLife,staticPageGenerationTimeout:T.staticPageGenerationTimeout,waitUntil:n.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,i,n,o)=>b.onRequestError(e,t,n,o,C)},sharedContext:{buildId:v,deploymentId:N}},G=new l.NodeNextRequest(e),Y=new l.NodeNextResponse(t),Z=c.NextRequestAdapter.fromNodeNextRequest(G,(0,c.signalFromNodeResponse)(t)),K=async({previousCacheEntry:i})=>{try{if(!q&&I&&A&&!i)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let o=await b.handle(Z,J);e.fetchMetrics=J.renderOpts.fetchMetrics;let s=J.renderOpts.pendingWaitUntil;s&&n.waitUntil&&(n.waitUntil(s),s=void 0);let r=J.renderOpts.collectedTags;if(!j)return await (0,u.sendResponse)(G,Y,o,s),null;{let e=await o.blob(),t=(0,m.toNodeOutgoingHttpHeaders)(o.headers);r&&(t[h.NEXT_CACHE_TAGS_HEADER]=r),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let i=void 0!==J.renderOpts.collectedRevalidate&&!(J.renderOpts.collectedRevalidate>=h.INFINITE_CACHE)&&J.renderOpts.collectedRevalidate,n=void 0===J.renderOpts.collectedExpire||J.renderOpts.collectedExpire>=h.INFINITE_CACHE?!1!==i&&i>0?T.expireTime:void 0:J.renderOpts.collectedExpire;return{value:{kind:y.CachedRouteKind.APP_ROUTE,status:o.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:i,expire:n}}}}catch(t){throw(null==i?void 0:i.isStale)&&await b.onRequestError(e,t,{routerKind:"App Router",routePath:w,routeType:"route",revalidateReason:(0,p.getRevalidateReason)({isStaticGeneration:M,isOnDemandRevalidate:I})},!1,C),t}},Q=async(o,r)=>{try{var a,l;let o=await b.handleResponse({req:e,nextConfig:T,cacheKey:D,routeKind:i.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:E,isRoutePPREnabled:!1,isOnDemandRevalidate:I,revalidateOnlyGenerated:A,responseGenerator:K,waitUntil:n.waitUntil,isMinimalMode:q});if(!j)return;if((null==o||null==(a=o.value)?void 0:a.kind)!==y.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==o||null==(l=o.value)?void 0:l.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});q||t.setHeader("x-nextjs-cache",I?"REVALIDATED":o.isMiss?"MISS":o.isStale?"STALE":"HIT"),P&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let s=(0,m.fromNodeOutgoingHttpHeaders)(o.value.headers);q&&j||s.delete(h.NEXT_CACHE_TAGS_HEADER),!o.cacheControl||t.getHeader("Cache-Control")||s.get("Cache-Control")||s.set("Cache-Control",(0,f.getCacheControlHeader)(o.cacheControl)),await (0,u.sendResponse)(G,Y,new Response(o.value.body,{headers:s,status:o.value.status||200}));return}catch(t){if(t instanceof g.NoFallbackError||await b.onRequestError(e,t,{routerKind:"App Router",routePath:_,routeType:"route",revalidateReason:(0,p.getRevalidateReason)({isStaticGeneration:M,isOnDemandRevalidate:I})},!1,C),j)throw t;await (0,u.sendResponse)(G,Y,new Response(null,{status:500}));return}finally{(()=>{if(!o)return;let e=t.statusCode;o.setAttributes({"http.status_code":e,"next.rsc":!1}),e&&e>=500&&(o.setStatus({code:s.SpanStatusCode.ERROR}),o.setAttribute("error.type",e.toString()));let i=z.getRootSpanAttributes();if(!i)return;if(i.get("next.span_type")!==d.BaseServerSpan.handleRequest)return console.warn(`Unexpected root span type '${i.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let n=i.get("next.route")||_,a=`${U} ${n}`;o.setAttributes({"next.route":n,"http.route":n,"next.span_name":a}),o.updateName(a),r&&r!==o&&(r.setAttribute("http.route",n),r.updateName(a))})()}};if(F&&L)await Q(L,void 0);else{let t=z.getActiveScopeSpan();await z.withPropagatedContext(e.headers,()=>z.trace(d.BaseServerSpan.handleRequest,{spanName:`${U} ${w}`,kind:s.SpanKind.SERVER,attributes:{"http.method":U,"http.target":e.url}},e=>Q(e,t)),void 0,!F)}}e.s(["handler",0,N,"patchFetch",0,function(){return(0,n.patchFetch)({workAsyncStorage:w,workUnitAsyncStorage:k})},"routeModule",0,b,"serverHooks",0,v,"workAsyncStorage",0,w,"workUnitAsyncStorage",0,k])}];
33
34
 
34
35
  //# sourceMappingURL=_1ek68ln._.js.map
@@ -0,0 +1,3 @@
1
+ module.exports=[91301,e=>{e.v(e=>Promise.resolve().then(()=>e(30441)))},37352,e=>{e.v(e=>Promise.resolve().then(()=>e(36203)))},5807,e=>{e.v(e=>Promise.resolve().then(()=>e(55851)))},97452,e=>{e.v(e=>Promise.resolve().then(()=>e(46413)))},52400,e=>{e.v(e=>Promise.resolve().then(()=>e(79364)))},62998,e=>{e.v(s=>Promise.all(["server/chunks/lib_factory-projects_ts_1eo_bk-._.js"].map(s=>e.l(s))).then(()=>s(69391)))},31854,e=>{e.v(e=>Promise.resolve().then(()=>e(69164)))},67347,e=>{e.v(e=>Promise.resolve().then(()=>e(64828)))},38978,e=>{e.v(e=>Promise.resolve().then(()=>e(90624)))},82978,e=>{e.v(e=>Promise.resolve().then(()=>e(35435)))},45093,e=>{e.v(e=>Promise.resolve().then(()=>e(19791)))},78081,e=>{e.v(s=>Promise.all(["server/chunks/[externals]__0h0p9dm._.js","server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_01r25oi._.js"].map(s=>e.l(s))).then(()=>s(39702)))}];
2
+
3
+ //# sourceMappingURL=_1lbh81u._.js.map
@@ -0,0 +1,3 @@
1
+ module.exports=[17694,e=>{"use strict";var t=e.i(2157);e.i(50227);var i=e.i(79857);let r={mode:"oss",daemon:{configured:!1},collector:{sessions:!1,hooks:!0,hooksVerbosity:"decisions",redact:"minimal",environment:"local"},telemetry:{enabled:!0},audit:{auto:!1,intervalDays:7}};e.s(["isTelemetryEnabled",0,function(){if("1"===process.env.FAILPROOFAI_TELEMETRY_DISABLED)return!1;try{return function(){try{var e;let r,n,a,s,o;return e=JSON.parse((0,t.readFileSync)((0,i.configFile)(),"utf8")),r=e.mode?.kind,n=e.daemon??{},a=e.collector??{},s=e.telemetry??{},o=e.audit??{},{mode:"cloud"===r?"cloud":"oss",daemon:{configured:!0===n.configured},collector:{sessions:!0===a.sessions,hooks:!1!==a.hooks,hooksVerbosity:"all"===a.hooks_verbosity||"off"===a.hooks_verbosity?a.hooks_verbosity:"decisions",redact:"off"===a.redact?"off":"minimal",environment:"string"==typeof a.environment?a.environment:"local",machineId:"string"==typeof a.machine_id?a.machine_id:void 0,sources:function(e){if(!e||"object"!=typeof e||Array.isArray(e))return;let t={};for(let[i,r]of Object.entries(e)){if(!r||"object"!=typeof r||Array.isArray(r))continue;let e=r.extra_paths;if(!Array.isArray(e))continue;let n=e.filter(e=>"string"==typeof e&&""!==e.trim());n.length>0&&(t[i]={extraPaths:n})}return Object.keys(t).length>0?t:void 0}(a.sources)},telemetry:{enabled:!1!==s.enabled},audit:{auto:!0===o.auto,intervalDays:function(e){if("number"!=typeof e||!Number.isFinite(e))return 7;let t=Math.floor(e);return t<1?7:Math.min(t,90)}(o.interval_days),reportsConsentedAt:"number"==typeof o.reports_consented_at&&Number.isFinite(o.reports_consented_at)?o.reports_consented_at:void 0}}}catch{return structuredClone(r)}}().telemetry.enabled}catch{return!0}}],17694)},10659,e=>{"use strict";let t;var i=e.i(2157),r=e.i(50227),n=e.i(60526),a=e.i(66680);e.i(74533);var s=e.i(79857);let o=r.default.join(n.default.homedir(),".failproofai"),l=r.default.join(o,"instance-id");function c(e){return a.default.createHmac("sha256","failproofai-telemetry-v1").update(e).digest("hex")}function d(e){let t;try{if(t=(0,s.telemetryIdFile)(),i.default.readFileSync(t,"utf-8").trim()===e)return}catch{try{t=(0,s.telemetryIdFile)()}catch{return}}try{i.default.mkdirSync(r.default.dirname(t),{recursive:!0});let n=`${t}.${process.pid}.tmp`;i.default.writeFileSync(n,e,{encoding:"utf-8",mode:384}),i.default.renameSync(n,t)}catch{}}e.s(["getInstanceId",0,function(){if(t)return t;let e=function(){try{for(let e of(n.default.platform(),["/etc/machine-id","/var/lib/dbus/machine-id"]))try{let t=i.default.readFileSync(e,"utf-8").trim();if(t)return t}catch{}}catch{}}();if(e)return d(t=c(e)),t;let r=[n.default.hostname(),n.default.homedir(),n.default.platform(),n.default.arch(),n.default.cpus()[0]?.model??""].join(":");return r?d(t=c(r)):d(t=function(){try{let e=i.default.readFileSync(l,"utf-8").trim();if(e)return e}catch{}let e=a.default.randomUUID();try{i.default.mkdirSync(o,{recursive:!0}),i.default.writeFileSync(l,e,"utf-8")}catch{}return e}()),t}])},46501,e=>{"use strict";var t=e.i(10659),i=e.i(17694),r=e.i(24214),n=e.i(28067);let a=n.POSTHOG_API_KEY;async function s(){try{if(!(0,i.isTelemetryEnabled)()||globalThis.__FAILPROOFAI_POSTHOG__)return;let t=await e.A(78081),r=process.env.FAILPROOFAI_POSTHOG_KEY??a,n=process.env.FAILPROOFAI_POSTHOG_HOST??"https://us.i.posthog.com";globalThis.__FAILPROOFAI_POSTHOG__=new t.PostHog(r,{host:n,flushAt:1,flushInterval:1e4,requestTimeout:1e4,fetchRetryCount:3,fetchRetryDelay:3e3});let s=!1,o=()=>{s||(s=!0,globalThis.__FAILPROOFAI_POSTHOG__?.shutdown().catch(()=>{}))};process.on("beforeExit",o),process.on("SIGTERM",o),process.on("SIGINT",o)}catch(e){console.warn("[failproofai:telemetry] init failed:",e instanceof Error?e.message:e)}}e.s(["initTelemetry",0,s,"trackEvent",0,function(e,a){if(!(0,i.isTelemetryEnabled)())return;let s=globalThis.__FAILPROOFAI_POSTHOG__;s&&s.capture({distinctId:(0,t.getInstanceId)(),event:e,properties:{...a,$lib:"failproofai",failproofai_version:r.version,product:n.POSTHOG_PRODUCT}})}])},24214,(e,t,i)=>{t.exports={name:"failproofai",version:"1.0.2-beta.4",description:"Observability and enforcement for AI agent harnesses. 39 built-in policies hooked into 12 of them — Claude Code, Codex, Cursor, Hermes, OpenClaw and more — blocking the tool call before it runs. Local dashboard included, no account needed.",bin:{failproofai:"./dist/cli.mjs",failproofaid:"./bin/failproofaid-shim.mjs"},files:["bin/","src/","scripts/","lib/","pi-extension/","openclaw-plugin/",".next/standalone/","dist/","README.md"],engines:{node:">=20.9.0",bun:">=1.3.0"},scripts:{predev:"bun run build:cli && bun link",dev:"FAILPROOFAI_TELEMETRY_DISABLED=1 bun scripts/dev.ts --port 8020","build:cli":"bun build --target=node --format=esm --outfile=dist/cli.mjs bin/failproofai.mjs --external posthog-node --external sql.js && node -e \"const fs=require('fs');const c=fs.readFileSync('dist/cli.mjs','utf8');fs.writeFileSync('dist/cli.mjs',c.replace('#!/usr/bin/env bun','#!/usr/bin/env node').replace('// @bun\\n',''))\"","build:worker":"bun build --target=node --format=esm --outfile=dist/worker.mjs bin/failproofai-worker.mjs --external posthog-node --external sql.js",build:"bun build --target=node --format=cjs --outfile=dist/index.js src/index.ts && bun run build:cli && bun run build:worker && bun --bun next build && node -e \"const {cpSync}=require('fs');cpSync('.next/static','.next/standalone/.next/static',{recursive:true});\" && node scripts/prune-standalone.mjs",prestart:"bun run build:cli && bun link",start:"FAILPROOFAI_TELEMETRY_DISABLED=1 bun scripts/start.ts",test:"vitest","test:run":"vitest run",lint:"eslint . --config eslint.config.mjs",prepare:"bun run build","test:e2e":"vitest run --config vitest.config.e2e.mts","test:e2e:watch":"vitest --config vitest.config.e2e.mts",translate:"bun scripts/translate-docs/cli.ts","translate:readme":"bun scripts/translate-docs/cli.ts --readme-only","translate:docs":"bun scripts/translate-docs/cli.ts --docs-only","translate:dry-run":"bun scripts/translate-docs/cli.ts --dry-run","translate:validate":"bun scripts/translate-docs/cli.ts --validate","validate:mdx":"bun scripts/validate-mdx.ts","docs:audit":"bun scripts/docs-audit.ts","build:pack":"bun scripts/build-policy-pack.mjs"},keywords:["agent-observability","llm-observability","agent-tracing","agent-monitoring","agent-harness","guardrails","enforcement","policies","evals","ai-agent","autonomous-agent","agent-reliability","failure-prevention","claude-code","codex","hermes","openclaw","cli","local-first","hooks"],author:"ExosphereHost Inc. <failproofai@exosphere.host>",license:"SEE LICENSE IN LICENSE",homepage:"https://github.com/FailproofAI/failproofai",repository:{type:"git",url:"https://github.com/FailproofAI/failproofai.git"},bugs:{url:"https://github.com/FailproofAI/failproofai/issues"},publishConfig:{access:"public"},devDependencies:{"@anthropic-ai/sdk":"^0.120.0","@mdx-js/mdx":"^3.1.1","@tailwindcss/postcss":"^4.3.1","@tanstack/react-virtual":"^3.14.10","@testing-library/jest-dom":"^7.0.0","@testing-library/react":"^16.3.2","@testing-library/user-event":"^14.6.5","@types/node":"26.2.0","@types/react":"19.2.18","@types/react-dom":"^19.2.3","@vitejs/plugin-react":"^6.1.0",clsx:"^2.1.1",eslint:"^10.9.0","eslint-config-next":"^16.3.2",jsdom:"^30.0.1","lucide-react":"^1.33.0",next:"^16.3.2",react:"^19.2.4","react-dom":"^19.2.4","tailwind-merge":"^3.4.0",tailwindcss:"^4.3.1",typescript:"6.0.3",vitest:"^4.1.11"},dependencies:{"html-to-image":"^1.11.13","posthog-node":"^5.50.0","sql.js":"^1.14.1",yaml:"^2.9.0"},overrides:{nanoid:"3.3.18",postcss:"8.5.26","eslint-plugin-react-hooks":"7.0.1",vite:"8.0.16",undici:"7.29.0","brace-expansion":"5.0.9",sharp:"0.35.0"},optionalDependencies:{"@failproofai/failproofaid-linux-x64":"1.0.2-beta.4","@failproofai/failproofaid-linux-arm64":"1.0.2-beta.4","@failproofai/failproofaid-darwin-x64":"1.0.2-beta.4","@failproofai/failproofaid-darwin-arm64":"1.0.2-beta.4"},failproofaidBinaries:{"linux-x64":"08bc00a7f8d7c80bf898471ce59c57f4e96c1420080009cc933b2ddeb4f23750","linux-arm64":"1167d809628cff04c38efbc0eaa83ca26ab8de2878bed0ef59ca43054173eea7","darwin-x64":"6ed32db21af6869c4475e753e524ad8e128436674209ad778421b240a4bd5c53","darwin-arm64":"3843de034c9d6b11f77c1f423e6201ad6a77b7eff3b3d4460ba324c5aeb62021"}}},28067,e=>{"use strict";e.s(["POSTHOG_API_KEY",0,"phc_Ac1Ww1GqKc0z1SyrRWbmatEeQdlOQIsDEEdP8l8JRgX","POSTHOG_PRODUCT",0,"failproofai-oss"])}];
2
+
3
+ //# sourceMappingURL=_1zuiiy3._.js.map